Last active
January 30, 2016 19:21
-
-
Save makiftasova/e97e747d1b20a9b123bb to your computer and use it in GitHub Desktop.
A sample code for handling bot commands with telepot.
This file contains hidden or 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 python3 | |
# -*- coding: utf-8 -*- | |
# | |
# Mehmet Akif TAŞOVA <[email protected]> | |
# A sample code for handling bot commands with telepot | |
# | |
import time | |
import telepot | |
BOT_TOKEN = "BOT_TOKEN_HERE" | |
tg_bot = 0 | |
tg_commands = {} | |
# return cmd, params | |
def parse_cmd(cmd_string): | |
text_split = cmd_string.split() | |
return text_split[0], text_split[1:] | |
def add_command(cmd, func): | |
global tg_commands | |
tg_commands[cmd] = func | |
def remove_command(cmd): | |
global tg_commands | |
del tg_commands[cmd] | |
def on_message(message): | |
global tg_bot | |
content_type, chat_type, chat_id = telepot.glance2(message) | |
if content_type == "text": | |
msg_text = message['text'] | |
chat_id = message['chat']['id'] | |
print("[MSG] {uid} : {msg}".format(uid=message['from']['id'], msg=msg_text)) | |
if msg_text[0] == '/': | |
cmd, params = parse_cmd(msg_text) | |
try: | |
tg_commands[cmd](chat_id, params) | |
except KeyError: | |
tg_bot.sendMessage(chat_id, "Unknown command: {cmd}".format(cmd=cmd)) | |
else: | |
tg_bot.sendMessage(chat_id, "Message is a plain text") | |
def cmd_echo(chat_id, params): | |
tg_bot.sendMessage(chat_id, "[ECHO] {text}".format(text=" ".join(params))) | |
def main(): | |
global tg_bot | |
tg_bot = telepot.Bot(BOT_TOKEN) | |
add_command("/echo", cmd_echo) | |
tg_bot.notifyOnMessage(on_message) | |
print("Listening messages") | |
if __name__ == "__main__": | |
main() | |
while True: | |
time.sleep(10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment