Skip to content

Instantly share code, notes, and snippets.

@VycktorStark
Last active August 13, 2020 15:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VycktorStark/f65c7842ffccf6b29b2598628b0c02af to your computer and use it in GitHub Desktop.
Save VycktorStark/f65c7842ffccf6b29b2598628b0c02af to your computer and use it in GitHub Desktop.
Simple bot with polling - TELEGRAM BOT
__author__ = "Vycktor Stark"
"""
This is a simple project to run a bot on the telegram via polling (webscraping) without using a module or lib
to start the code, after the download, just first insert your bot key to it and run as follows: `python3 main.py`
Note: I am aware that it is much more practical to use the / lib module to create the code faster,
but the goal of this snippet is to demonstrate an alternative for you to create the code your way
"""
from threading import Thread
import json, requests, re, time
SECRET_KEY = '690665975:AAH6WVlaNp89wNZrje-oqzRB4PWhNrvvxok' # Define your bot's token
TELEGRAM_API = f'https://api.telegram.org/bot{SECRET_KEY}'
def handler(vetor):
"""
This function will receive events, but will only handle events that have the key: "message",
if so, it will respond to all events with the word: PONG
except, if the event has a command equal to "/pong", in this case, it will respond: PING
Note: the returns are just examples, you can change or add the way you prefer.
"""
if ("message" in vetor):
msg = vetor["message"]
params = dict(chat_id = msg['chat']['id'], text = 'PONG')
if ('text' in msg):
bloco = msg['text'].lower().split()
if ('/pong' in bloco[0]): params['text'] = 'PONG'
requests.post(f"{TELEGRAM_API}/sendMessage", params=params, headers={'Content-Type':'application/json'})
def polling():
"""
This function will be responsible for "polling" (web scraping) in the "API-TELEGRAM-BOT"
and inserting what to collect in the "handler" function
"""
temp = 100
while True:
data = requests.get(f"{TELEGRAM_API}/getUpdates", params=dict(offset=temp, timeout=int(temp+1), allowd_updates='message'), headers={"Content-Type": "application/json"})
data = dict(data.json())
if len(data["result"]) == 0:
resp = json.dumps(dict(ping='pong')) #Defined something to return, if no results are found
elif ("result" in data):
temp = int(data['result'][0]['update_id'] + 1) #Increasing time
resp = data['result'][0]
handler(resp)
if __name__ == '__main__':
try:
reading = Thread(target=polling(), args=())
reading.setDaemon(True)
reading.start()
except KeyboardInterrupt:
print("\nending bot")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment