Created
July 3, 2018 19:28
-
-
Save murilobsd/d59d57211594161ce4448c07bd907cd2 to your computer and use it in GitHub Desktop.
Telegram Bot example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from __future__ import print_function | |
import datetime | |
import os | |
import random | |
import re | |
import time | |
import telepot | |
from telepot.loop import MessageLoop | |
# token environ | |
tg_token = os.environ.get('TELEGRAM_TOKEN', 'XXX') | |
# create bot | |
bot = telepot.Bot(tg_token) | |
# regex commands | |
re_cmd = re.compile(r"\/(\w+)\s?") | |
def dht(): | |
"""Temperature""" | |
return 22.2 | |
def _random(): | |
return random.randint(1,6) | |
def _now(): | |
return str(datetime.datetime.now()) | |
commands = { | |
'roll': { | |
'run': _random, | |
'description': "juego de la adivinación", | |
}, | |
'hora': { | |
'run': _now, | |
'description': "hora de ahora", | |
}, | |
'temp': { | |
'run': dht, | |
'description': "temperatura de la ....", | |
} | |
} | |
def _help(): | |
"""Description all helpers.""" | |
list_commands = "" | |
for key in commands.keys(): | |
if 'description' in commands[key]: | |
list_commands += "/{} - {}\n".format(key, commands[key]['description']) | |
list_commands += "/help ayudar" | |
return list_commands | |
def excute_command(chat_id, command): | |
"""Execute command.""" | |
if command == 'help': | |
bot.sendMessage(chat_id, _help()) | |
return | |
if command in commands.keys(): | |
try: | |
bot.sendMessage(chat_id, commands[command]['run']()) | |
except Exception as e: | |
print(e) | |
bot.sendMessage(chat_id, "Op's algún problema ocurrió") | |
return | |
else: | |
bot.sendMessage(chat_id, "command not found. type /help") | |
return | |
def handle(msg): | |
chat_id = msg['chat']['id'] | |
command = re_cmd.match(msg['text']) | |
if command: | |
command = command[0][1:] # simple way to remove / | |
print('Got command: %s from : %s' % (command, str(chat_id))) | |
excute_command(chat_id, command) | |
else: | |
bot.sendMessage(chat_id, "command not found. type /help") | |
def main(): | |
"""Main function.""" | |
MessageLoop(bot, handle).run_as_thread() | |
print('En linea ...') | |
while 1: | |
time.sleep(10) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
execute: