Skip to content

Instantly share code, notes, and snippets.

@exiva
Created January 13, 2017 06:39
Show Gist options
  • Save exiva/84edf2cdd90fc126dd55bd398e7d1d0a to your computer and use it in GitHub Desktop.
Save exiva/84edf2cdd90fc126dd55bd398e7d1d0a to your computer and use it in GitHub Desktop.
boilerplate telegram bot code with decorators for admin, private chat and public chat.
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters)
from functools import wraps
def admin_required(func):
@wraps(func)
def getAdmins(bot, chat_id):
return [admin.user.id for admin in bot.getChatAdministrators(chat_id)]
def check_admin(*args, **kwargs):
if args[1].message.chat.type == "private":
return func(*args, **kwargs)
elif args[1].message.from_user.id in getAdmins(args[0], args[1].message.chat_id):
return func(*args, **kwargs)
return check_admin
def chat(func):
@wraps(func)
def public_command(*args, **kwargs):
if args[1].message.chat.type != "private":
return func(*args, **kwargs)
return public_command
def private(func):
@wraps(func)
def private_command(*args, **kwargs):
if args[1].message.chat.type == "private":
return func(*args, **kwargs)
return private_command
def echo(bot, update):
bot.sendMessage(update.message.chat_id, "Hm? Echo?")
@admin_required
def start(bot, update):
bot.sendMessage(update.message.chat_id, "I'd execute a start command here.")
@chat
def test_public(bot, update):
bot.sendMessage(update.message.chat_id, "This is a chat only command")
@private
def test_private(bot, update):
bot.sendMessage(update.message.chat_id, "This only works in private messages")
def main():
updater = Updater(YOURAPIKEY)
dp = updater.dispatcher
dp.add_handler(MessageHandler(Filters.text, echo))
dp.add_handler(CommandHandler('start', start))
dp.add_handler(CommandHandler('public', test_public))
dp.add_handler(CommandHandler('private', test_private))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment