def test_with_pattern(self, callback_query): handler = CallbackQueryHandler(self.callback_basic, pattern='.*est.*') assert handler.check_update(callback_query) callback_query.callback_query.data = 'nothing here' assert not handler.check_update(callback_query)
def test_basic(self, dp, callback_query): handler = CallbackQueryHandler(self.callback_basic) dp.add_handler(handler) assert handler.check_update(callback_query) dp.process_update(callback_query) assert self.test_flag
bot.answer_callback_query(query.id) if query_type == "db_leave_chat": if query.from_user.id in admin_list: bot.editMessageText("Leaving chats ...", chat_id, message.message_id) chat_count = get_muted_chats(update, context, True) bot.sendMessage(chat_id, f"Left {chat_count} chats.") else: query.answer("You are not allowed to use this.") elif query_type == "db_cleanup": if query.from_user.id in admin_list: bot.editMessageText("Cleaning up DB ...", chat_id, message.message_id) invalid_chat_count = get_invalid_chats(update, context, True) invalid_gban_count = get_invalid_gban(update, context, True) reply = "Cleaned up {} chats and {} gbanned users from db.".format( invalid_chat_count, invalid_gban_count ) bot.sendMessage(chat_id, reply) else: query.answer("You are not allowed to use this.") DB_CLEANUP_HANDLER = CommandHandler("dbcleanup", dbcleanup) BUTTON_HANDLER = CallbackQueryHandler(callback_button, pattern="db_.*") dispatcher.add_handler(DB_CLEANUP_HANDLER) dispatcher.add_handler(BUTTON_HANDLER) __mod_name__ = "DB Cleanup" __handlers__ = [DB_CLEANUP_HANDLER, BUTTON_HANDLER]
query.answer() # query.edit_message_text(text="Selected option: {}".format(query.data)) def button1(update, context): query = update.callback_query # CallbackQueries need to be answered, even if no notification to the user is needed # Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery query.answer() query.edit_message_text(text="Selected option: {}".format(query.data)) updater.dispatcher.add_handler(CallbackQueryHandler(button)) def start(update, context): keyboard = [[ InlineKeyboardButton("Option 1", callback_data='1'), InlineKeyboardButton("Option 2", callback_data='2') ], [InlineKeyboardButton("Option 3", callback_data='3')]] reply_markup = InlineKeyboardMarkup(keyboard) update.message.reply_text('Please choose:', reply_markup=reply_markup) updater.dispatcher.add_handler(CommandHandler('start', start)) ############################vahid
filters=Filters.group) RESET_GOODBYE = CommandHandler("resetgoodbye", reset_goodbye, filters=Filters.group) WELCOMEMUTE_HANDLER = CommandHandler("welcomemute", welcomemute, filters=Filters.group) CLEAN_SERVICE_HANDLER = CommandHandler("cleanservice", cleanservice, filters=Filters.group) CLEAN_WELCOME = CommandHandler("cleanwelcome", clean_welcome, filters=Filters.group) WELCOME_HELP = CommandHandler("welcomehelp", welcome_help) WELCOME_MUTE_HELP = CommandHandler("welcomemutehelp", welcome_mute_help) BUTTON_VERIFY_HANDLER = CallbackQueryHandler(user_button, pattern=r"user_join_") dispatcher.add_handler(NEW_MEM_HANDLER) dispatcher.add_handler(LEFT_MEM_HANDLER) dispatcher.add_handler(WELC_PREF_HANDLER) dispatcher.add_handler(GOODBYE_PREF_HANDLER) dispatcher.add_handler(SET_WELCOME) dispatcher.add_handler(SET_GOODBYE) dispatcher.add_handler(RESET_WELCOME) dispatcher.add_handler(RESET_GOODBYE) dispatcher.add_handler(CLEAN_WELCOME) dispatcher.add_handler(WELCOME_HELP) dispatcher.add_handler(WELCOMEMUTE_HANDLER) dispatcher.add_handler(CLEAN_SERVICE_HANDLER) dispatcher.add_handler(BUTTON_VERIFY_HANDLER) dispatcher.add_handler(WELCOME_MUTE_HELP)
`/save notename` while replying to a sticker or whatever data you'd like. Now, the note at "#notename" contains a sticker which will be sent as a reply. Tip: to retrieve a note without the formatting, use /get <notename> noformat This will retrieve the note and send it without formatting it; getting you the raw markdown, allowing you to make easy edits. """ __mod_name__ = "Notes" GET_HANDLER = CommandHandler("get", cmd_get, pass_args=True) HASH_GET_HANDLER = MessageHandler(Filters.regex(r"^#[^\s]+"), hash_get) SAVE_HANDLER = CommandHandler("save", save) DELETE_HANDLER = CommandHandler("clear", clear, pass_args=True) LIST_HANDLER = DisableAbleCommandHandler(["notes", "saved"], list_notes, admin_ok=True) CLEARALLNOTES_HANDLER = CommandHandler("clearall", clear_notes, filters=Filters.group) RMBTN_HANDLER = CallbackQueryHandler(rmbutton, pattern=r"rmnotes_") dispatcher.add_handler(GET_HANDLER) dispatcher.add_handler(SAVE_HANDLER) dispatcher.add_handler(LIST_HANDLER) dispatcher.add_handler(DELETE_HANDLER) dispatcher.add_handler(HASH_GET_HANDLER) dispatcher.add_handler(CLEARALLNOTES_HANDLER) dispatcher.add_handler(RMBTN_HANDLER)
parse_mode=ParseMode.HTML, ) query.answer("❎ Failed to delete message!") __mod_name__ = "Reporting" __help__ = """ - /report <reason>: reply to a message to report it to admins. - @admin: reply to a message to report it to admins. NOTE: neither of these will get triggered if used by admins *Admin only:* - /reports <on/off>: change report setting, or view current status. - If done in pm, toggles your status. - If in chat, toggles that chat's status. """ REPORT_HANDLER = CommandHandler("report", report, filters=Filters.group) SETTING_HANDLER = CommandHandler("reports", report_setting, pass_args=True) ADMIN_REPORT_HANDLER = RegexHandler("(?i)@admin(s)?", report) cntrl_panel_user_callback_handler = CallbackQueryHandler( control_panel_user, pattern=r"panel_reporting_U") report_button_user_handler = CallbackQueryHandler(buttons, pattern=r"report_") dispatcher.add_handler(cntrl_panel_user_callback_handler) dispatcher.add_handler(report_button_user_handler) dispatcher.add_handler(REPORT_HANDLER, REPORT_GROUP) dispatcher.add_handler(ADMIN_REPORT_HANDLER, REPORT_GROUP) dispatcher.add_handler(SETTING_HANDLER)
from random import randint from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, CallbackContext from telegram import InlineKeyboardMarkup, InlineKeyboardButton, Update def start(update: Update, context: CallbackContext): a, b = randint(1, 100), randint(1, 100) update.message.reply_text('{} + {} = ?'.format(a, b), reply_markup = InlineKeyboardMarkup([[ InlineKeyboardButton(str(s), callback_data = '{} {} {}'.format(a, b, s)) for s in range(a + b - randint(1, 3), a + b + randint(1, 3)) ]])) def answer(update: Update, context: CallbackContext): a, b, s = [int(x) for x in update.callback_query.data.split()] if a + b == s: update.callback_query.edit_message_text('你答對了!') else: update.callback_query.edit_message_text('你答錯囉!') updater = Updater('1375267822:AAEiFLybctSwv647TOeIQYSLX5TGY_fbFQg',use_context=True) updater.dispatcher.add_handler(CommandHandler('start', start)) updater.dispatcher.add_handler(CallbackQueryHandler(answer)) updater.start_polling() updater.idle()
➢ `/warnlimit <num>`*:* set the warning limit ➢ `/strongwarn <on/yes/off/no>`*:* If set to on, exceeding the warn limit will result in a ban. Else, will just kick. """ __mod_name__ = "Warnings" WARN_HANDLER = CommandHandler(["warn", "dwarn"], warn_user, filters=Filters.chat_type.groups, run_async=True) RESET_WARN_HANDLER = CommandHandler(["resetwarn", "resetwarns"], reset_warns, filters=Filters.chat_type.groups, run_async=True) CALLBACK_QUERY_HANDLER = CallbackQueryHandler(button, pattern=r"rm_warn", run_async=True) MYWARNS_HANDLER = DisableAbleCommandHandler("warns", warns, filters=Filters.chat_type.groups, run_async=True) ADD_WARN_HANDLER = CommandHandler("addwarn", add_warn_filter, filters=Filters.chat_type.groups) RM_WARN_HANDLER = CommandHandler(["nowarn", "stopwarn"], remove_warn_filter, filters=Filters.chat_type.groups) LIST_WARN_HANDLER = DisableAbleCommandHandler(["warnlist", "warnfilters"], list_warn_filters, filters=Filters.chat_type.groups, admin_ok=True,
elif "file" in url: return "file" elif "/#F!" in url: return "folder" return "file" def is_magnet(url: str): magnet = re.findall(MAGNET_REGEX, url) if magnet: return True return False def new_thread(fn): """To use as decorator to make a function call threaded. Needs import from threading import Thread""" def wrapper(*args, **kwargs): thread = threading.Thread(target=fn, args=args, kwargs=kwargs) thread.start() return thread return wrapper next_handler = CallbackQueryHandler(flip, pattern="nex", run_async=True) previous_handler = CallbackQueryHandler(flip, pattern="pre", run_async=True) dispatcher.add_handler(next_handler) dispatcher.add_handler(previous_handler)
def __init__(self, instance_id: str = None): """ Initialization. """ super().__init__(instance_id) # Check PIL support for WebP Image.init() if 'WEBP' not in Image.ID: raise EFBException(self._("WebP support of Pillow is required.\n" "Please refer to Pillow Documentation for instructions.\n" "https://pillow.readthedocs.io/")) # Suppress debug logs from dependencies logging.getLogger('requests').setLevel(logging.CRITICAL) logging.getLogger('urllib3').setLevel(logging.CRITICAL) logging.getLogger('telegram.bot').setLevel(logging.CRITICAL) logging.getLogger('telegram.vendor.ptb_urllib3.urllib3.connectionpool').setLevel(logging.CRITICAL) # Set up logger self.logger: logging.Logger = logging.getLogger(__name__) # Load configs self.load_config() # Load predefined MIME types mimetypes.init(files=["mimetypes"]) # Initialize managers self.flag: ExperimentalFlagsManager = ExperimentalFlagsManager(self) self.db: DatabaseManager = DatabaseManager(self) self.bot_manager: TelegramBotManager = TelegramBotManager(self) # self.voice_recognition: VoiceRecognitionManager = VoiceRecognitionManager(self) self.chat_binding: ChatBindingManager = ChatBindingManager(self) self.commands: CommandsManager = CommandsManager(self) self.master_messages: MasterMessageProcessor = MasterMessageProcessor(self) self.slave_messages: SlaveMessageProcessor = SlaveMessageProcessor(self) if not self.flag('auto_locale'): self.translator = translation("efb_telegram_master", resource_filename('efb_telegram_master', 'locale'), fallback=True) # Basic message handlers self.bot_manager.dispatcher.add_handler( GlobalCommandHandler("start", self.start, pass_args=True)) self.bot_manager.dispatcher.add_handler( CommandHandler("help", self.help)) self.bot_manager.dispatcher.add_handler( GlobalCommandHandler("info", self.info)) self.bot_manager.dispatcher.add_handler( CallbackQueryHandler(self.void_callback_handler, pattern="void")) self.bot_manager.dispatcher.add_handler( CallbackQueryHandler(self.bot_manager.session_expired)) self.bot_manager.dispatcher.add_handler( GlobalCommandHandler("react", self.react) ) self.bot_manager.dispatcher.add_error_handler(self.error) self.rpc_utilities = RPCUtilities(self)
def init(dispatcher: Dispatcher): """Provide handlers initialization.""" dispatcher.add_handler(CallbackQueryHandler(cancel, pattern=r'^cancel$'))
Reply 3` ❍ /clear <notename>*:* clear note with this name ❍ /removeallnotes*:* removes all notes from the group *Note:* Note names are case-insensitive, and they are automatically converted to lowercase before getting saved. """ __mod_name__ = "NOTES" GET_HANDLER = CommandHandler("get", cmd_get) HASH_GET_HANDLER = MessageHandler(Filters.regex(r"^#[^\s]+"), hash_get) SLASH_GET_HANDLER = MessageHandler(Filters.regex(r"^/\d+$"), slash_get) SAVE_HANDLER = CommandHandler("save", save) DELETE_HANDLER = CommandHandler("clear", clear) LIST_HANDLER = DisableAbleCommandHandler(["notes", "saved"], list_notes, admin_ok=True) CLEARALL = DisableAbleCommandHandler("removeallnotes", clearall) CLEARALL_BTN = CallbackQueryHandler(clearall_btn, pattern=r"notes_.*") dispatcher.add_handler(GET_HANDLER) dispatcher.add_handler(SAVE_HANDLER) dispatcher.add_handler(LIST_HANDLER) dispatcher.add_handler(DELETE_HANDLER) dispatcher.add_handler(HASH_GET_HANDLER) dispatcher.add_handler(SLASH_GET_HANDLER) dispatcher.add_handler(CLEARALL) dispatcher.add_handler(CLEARALL_BTN)
__mod_name__ = "Tagger" __help__ = """ Tagger is an essential feature to mention all subscribed members in the group. Any chat members can subscribe to tagger. - /tagme: registers to the chat tag list. - /untagme: unsubscribes from the chat tag list. *Admin only:* - /tagall: mention all subscribed members. - /untagall: clears all subscribed members. - /addtag <userhandle>: add a user to chat tag list. (via handle, or reply) - /removetag <userhandle>: remove a user to chat tag list. (via handle, or reply) """ TAG_ALL_HANDLER = DisableAbleCommandHandler("tagall", tagall, filters=Filters.group) UNTAG_ALL_HANDLER = DisableAbleCommandHandler("untagall", untagall, filters=Filters.group) UNTAG_ME_HANDLER = CommandHandler("untagme", untagme, filters=Filters.group) TAG_ME_HANDLER = CommandHandler("tagme", tagme, filters=Filters.group) ADD_TAG_HANDLER = DisableAbleCommandHandler("addtag", addtag, pass_args=True, filters=Filters.group) REMOVE_TAG_HANDLER = DisableAbleCommandHandler("removetag", removetag, pass_args=True, filters=Filters.group) TAGALL_CALLBACK_HANDLER = CallbackQueryHandler(tagg_all_button, pattern=r"tagall_") dispatcher.add_handler(TAG_ALL_HANDLER) dispatcher.add_handler(UNTAG_ALL_HANDLER) dispatcher.add_handler(UNTAG_ME_HANDLER) dispatcher.add_handler(TAG_ME_HANDLER) dispatcher.add_handler(ADD_TAG_HANDLER) dispatcher.add_handler(REMOVE_TAG_HANDLER) dispatcher.add_handler(TAGALL_CALLBACK_HANDLER)
def main(): t_bot = telegram.Bot(token=constants.EXTREPYTHON_BOT_TOKEN) print(t_bot.get_me()) updater = Updater(token=constants.EXTREPYTHON_BOT_TOKEN) dispatcher = updater.dispatcher logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) awesome_filter = AwesomeFilter() #commands handlers start_command_handler = CommandHandler('start', commands.start) chat_id_handler = CommandHandler('chatId', commands.chat_id) inline_keyboard_handler = CommandHandler('keyboard', commands.inline_keyboard) timer_handler = CommandHandler('set', commands.set_timer, pass_args=True, pass_job_queue=True, pass_chat_data=True) unset_timer_handler = CommandHandler('unset', commands.unset, pass_chat_data=True) homer_handler = CommandHandler('homer', commands.homer) python_handler = CommandHandler('python', commands.python) emoji_handler = CommandHandler('emoji', commands.emoji, pass_args=True) caps_handler = CommandHandler('caps', commands.caps, pass_args=True) unknown_handler = MessageHandler(Filters.command, utils.unknown) #messages handlers awesome_handler = MessageHandler(awesome_filter, messages.awesome_callback) echo_handler = MessageHandler(Filters.text, messages.echo) callback_query_handler = CallbackQueryHandler(callback_queries.button) #echo_all_handler = MessageHandler(Filters.all, messages.echo_all, edited_updates=True) #inline query handlers inline_caps_handler = InlineQueryHandler(inline_queries.inline_query) #add commands handlers dispatcher.add_handler(start_command_handler) dispatcher.add_handler(chat_id_handler) dispatcher.add_handler(inline_keyboard_handler) dispatcher.add_handler(timer_handler) dispatcher.add_handler(unset_timer_handler) dispatcher.add_handler(python_handler) dispatcher.add_handler(emoji_handler) dispatcher.add_handler(homer_handler) #add messages handlers dispatcher.add_handler(awesome_handler) dispatcher.add_handler(echo_handler) dispatcher.add_handler(caps_handler) dispatcher.add_handler(callback_query_handler) dispatcher.add_handler(unknown_handler) #dispatcher.add_handler(echo_all_handler) #add inline queries handlers dispatcher.add_handler(inline_caps_handler) updater.start_polling()
× /allowconnect <yes/no>: izinkan pengguna untuk terhubung ke obrolan """ CONNECT_CHAT_HANDLER = CommandHandler("connect", connect_chat, pass_args=True, run_async=True) CONNECTION_CHAT_HANDLER = CommandHandler("connection", connection_chat, run_async=True) DISCONNECT_CHAT_HANDLER = CommandHandler("disconnect", disconnect_chat, run_async=True) ALLOW_CONNECTIONS_HANDLER = CommandHandler("allowconnect", allow_connections, pass_args=True, run_async=True) HELP_CONNECT_CHAT_HANDLER = CommandHandler("helpconnect", help_connect_chat, run_async=True) CONNECT_BTN_HANDLER = CallbackQueryHandler(connect_button, pattern=r"connect", run_async=True) dispatcher.add_handler(CONNECT_CHAT_HANDLER) dispatcher.add_handler(CONNECTION_CHAT_HANDLER) dispatcher.add_handler(DISCONNECT_CHAT_HANDLER) dispatcher.add_handler(ALLOW_CONNECTIONS_HANDLER) dispatcher.add_handler(HELP_CONNECT_CHAT_HANDLER) dispatcher.add_handler(CONNECT_BTN_HANDLER)
- /connect: connect a chat (Can be done in a group by /connect or /connect <chat id> in PM) - /connection: list connected chats - /disconnect: disconnect from a chat - /helpconnect: list available commands that can be done remotely *Admin only:* - /allowconnect <yes/no>: allow a user to connect to a chat """ CONNECT_CHAT_HANDLER = CommandHandler("connect", connect_chat, pass_args=True) CONNECTION_CHAT_HANDLER = CommandHandler("connection", connection_chat) DISCONNECT_CHAT_HANDLER = CommandHandler("disconnect", disconnect_chat) ALLOW_CONNECTIONS_HANDLER = CommandHandler("allowconnect", allow_connections, pass_args=True) HELP_CONNECT_CHAT_HANDLER = CommandHandler("helpconnect", help_connect_chat) CONNECT_BTN_HANDLER = CallbackQueryHandler(connect_button, pattern=r"connect") dispatcher.add_handler(CONNECT_CHAT_HANDLER) dispatcher.add_handler(CONNECTION_CHAT_HANDLER) dispatcher.add_handler(DISCONNECT_CHAT_HANDLER) dispatcher.add_handler(ALLOW_CONNECTIONS_HANDLER) dispatcher.add_handler(HELP_CONNECT_CHAT_HANDLER) dispatcher.add_handler(CONNECT_BTN_HANDLER) __mod_name__ = "CONNECTIONS" __handlers__ = [ CONNECT_CHAT_HANDLER, CONNECTION_CHAT_HANDLER, DISCONNECT_CHAT_HANDLER, ALLOW_CONNECTIONS_HANDLER, HELP_CONNECT_CHAT_HANDLER, CONNECT_BTN_HANDLER ]
RESET_GOODBYE = CommandHandler( "resetgoodbye", reset_goodbye, filters=Filters.chat_type.groups, run_async=True ) WELCOMEMUTE_HANDLER = CommandHandler( "welcomemute", welcomemute, filters=Filters.chat_type.groups, run_async=True ) CLEAN_SERVICE_HANDLER = CommandHandler( "cleanservice", cleanservice, filters=Filters.chat_type.groups, run_async=True ) CLEAN_WELCOME = CommandHandler( "cleanwelcome", clean_welcome, filters=Filters.chat_type.groups, run_async=True ) WELCOME_HELP = CommandHandler("welcomehelp", welcome_help, run_async=True) WELCOME_MUTE_HELP = CommandHandler("welcomemutehelp", welcome_mute_help, run_async=True) BUTTON_VERIFY_HANDLER = CallbackQueryHandler( user_button, pattern=r"user_join_", run_async=True ) CAPTCHA_BUTTON_VERIFY_HANDLER = CallbackQueryHandler( user_captcha_button, pattern=r"user_captchajoin_\([\d\-]+,\d+\)_\(\d{4}\)", run_async=True ) dispatcher.add_handler(NEW_MEM_HANDLER) dispatcher.add_handler(LEFT_MEM_HANDLER) dispatcher.add_handler(WELC_PREF_HANDLER) dispatcher.add_handler(GOODBYE_PREF_HANDLER) dispatcher.add_handler(SET_WELCOME) dispatcher.add_handler(SET_GOODBYE) dispatcher.add_handler(RESET_WELCOME) dispatcher.add_handler(RESET_GOODBYE) dispatcher.add_handler(CLEAN_WELCOME) dispatcher.add_handler(WELCOME_HELP)
def getJoke(update, context): joke = getRandomJoke() joke = Joke.factory(data=joke) keyboard = [[ InlineKeyboardButton("Punch", callback_data=str(joke.punchline)), ]] reply_markup = InlineKeyboardMarkup(keyboard) update.message.reply_text(text=joke.setup, reply_markup=reply_markup) def punch(update, context): query = update.callback_query query.answer() punch_line = query.data query.edit_message_text(text=punch_line) def developer(update, context): update.message.reply_text(text="Absera Temesgen") dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(MessageHandler(Filters.text("Random Joke"), getJoke)) updater.dispatcher.add_handler(CallbackQueryHandler(punch)) dispatcher.add_handler(MessageHandler(Filters.text("Developer"), developer)) updater.start_polling() print("...")
- /nowarn <keyword>: stop a warning filter - /warnlimit <num>: set the warning limit - /strongwarn <on/yes/off/no>: If set to on, exceeding the warn limit will result in a ban. Else, will just punch. """ __mod_name__ = "Warnings" WARN_HANDLER = CommandHandler("warn", warn_user, pass_args=True, filters=Filters.group) RESET_WARN_HANDLER = CommandHandler(["resetwarn", "resetwarns"], reset_warns, pass_args=True, filters=Filters.group) CALLBACK_QUERY_HANDLER = CallbackQueryHandler(button, pattern=r"rm_warn") MYWARNS_HANDLER = DisableAbleCommandHandler("warns", warns, pass_args=True, filters=Filters.group) ADD_WARN_HANDLER = CommandHandler("addwarn", add_warn_filter, filters=Filters.group) RM_WARN_HANDLER = CommandHandler(["nowarn", "stopwarn"], remove_warn_filter, filters=Filters.group) LIST_WARN_HANDLER = DisableAbleCommandHandler(["warnlist", "warnfilters"], list_warn_filters, filters=Filters.group, admin_ok=True) WARN_FILTER_HANDLER = MessageHandler(CustomFilters.has_text & Filters.group,
)) keyb = list(paginate(keyb, 2)) keyb.append([ InlineKeyboardButton( text="Help us in translations", url="https://poeditor.com/join/project?hash=oJISpjNcEx", ) ]) msg.reply_text(msg_text, reply_markup=InlineKeyboardMarkup(keyb)) @user_admin_no_reply def lang_button(update: Update, _) -> None: query = update.callback_query chat = update.effective_chat query.answer() lang = query.data.split("_")[1] sql.set_lang(chat.id, lang) query.message.edit_text( gs(chat.id, "set_chat_lang").format(get_language(lang)[:-3])) SETLANG_HANDLER = CommandHandler("language", set_lang) SETLANG_BUTTON_HANDLER = CallbackQueryHandler(lang_button, pattern=r"setLang_") dispatcher.add_handler(SETLANG_HANDLER) dispatcher.add_handler(SETLANG_BUTTON_HANDLER)
➢ `/removeallfilters`*:* Remove all chat filters at once. *Note*: Filters also support markdown formatters like: {first}, {last} etc.. and buttons. Check `/markdownhelp` to know more! """ __mod_name__ = "Filters" FILTER_HANDLER = DisableAbleCommandHandler("filter", filters) STOP_HANDLER = DisableAbleCommandHandler("stop", stop_filter) RMALLFILTER_HANDLER = DisableAbleCommandHandler( "removeallfilters", rmall_filters, filters=Filters.chat_type.groups, run_async=True) RMALLFILTER_CALLBACK = CallbackQueryHandler(rmall_callback, pattern=r"filters_.*", run_async=True) LIST_HANDLER = DisableAbleCommandHandler("filters", list_handlers, admin_ok=True, run_async=True) CUST_FILTER_HANDLER = MessageHandler(CustomFilters.has_text & ~Filters.update.edited_message, reply_filter, run_async=True) dispatcher.add_handler(FILTER_HANDLER) dispatcher.add_handler(STOP_HANDLER) dispatcher.add_handler(LIST_HANDLER) dispatcher.add_handler(CUST_FILTER_HANDLER, HANDLER_GROUP) dispatcher.add_handler(RMALLFILTER_HANDLER)
except TimedOut: print(context.error) # handle slow connection problems except NetworkError: print(context.error) # handle other connection problems except ChatMigrated as e: print(context.error) # the chat_id of a group has changed, use e.new_chat_id instead except TelegramError: print(context.error) # handle all other telegram related errors list_handler = CommandHandler('cx', list_command) dispatcher.add_handler(list_handler) my_handler = CommandHandler('my', my_command) dispatcher.add_handler(my_handler) mark_handler = CommandHandler('mark', mark_command) dispatcher.add_handler(mark_handler) help_handler = CommandHandler('help', help_command) dispatcher.add_handler(help_handler) callback_query_handler = CallbackQueryHandler(handle_list_callback, pattern='^list:') dispatcher.add_handler(callback_query_handler) my_callback_query_handler = CallbackQueryHandler(handle_driver_callback, pattern='^my:') dispatcher.add_handler(my_callback_query_handler) dispatcher.add_error_handler(error_callback) updater.start_polling()
import bot.main as bot from bot.secret import TELEGRAM_TOKEN if __name__ == "__main__": logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO) logger = logging.getLogger(__name__) # telegram bot init updater = Updater(token=TELEGRAM_TOKEN) dispatcher = updater.dispatcher # adds the functions to the bot function dispatcher.add_handler(CommandHandler("start", bot.start)) dispatcher.add_handler(CommandHandler("language", bot.choose_language)) dispatcher.add_handler( MessageHandler(filters.Filters.voice, bot.input_received)) dispatcher.add_handler( MessageHandler(filters.Filters.text, bot.input_received)) # button rating dispatcher.add_handler(CallbackQueryHandler(bot.response)) logger.info("--- Starting bot ---") # starts receiving calls updater.start_polling(timeout=10) updater.idle()
Maybe not enough to make them admin, but you might be ok with locks, blacklists, and antiflood not applying to them. That's what approvals are for - approve of trustworthy users to allow them to send *Admin commands:* ❍ /approval*:* Check a user's approval status in this chat. ❍ /approve*:* Approve of a user. Locks, blacklists, and antiflood won't apply to them anymore. ❍ /unapprove*:* Unapprove of a user. They will now be subject to locks, blacklists, and antiflood again. ❍ /approved*:* List all approved users. ❍ /unapproveall*:* Unapprove *ALL* users in a chat. This cannot be undone. """ APPROVE = DisableAbleCommandHandler("approve", approve) DISAPPROVE = DisableAbleCommandHandler("unapprove", disapprove) APPROVED = DisableAbleCommandHandler("approved", approved) APPROVAL = DisableAbleCommandHandler("approval", approval) UNAPPROVEALL = DisableAbleCommandHandler("unapproveall", unapproveall) UNAPPROVEALL_BTN = CallbackQueryHandler(unapproveall_btn, pattern=r"unapproveall_.*") dispatcher.add_handler(APPROVE) dispatcher.add_handler(DISAPPROVE) dispatcher.add_handler(APPROVED) dispatcher.add_handler(APPROVAL) dispatcher.add_handler(UNAPPROVEALL) dispatcher.add_handler(UNAPPROVEALL_BTN) __mod_name__ = "Approvals" __command_list__ = ["approve", "unapprove", "approved", "approval"] __handlers__ = [APPROVE, DISAPPROVE, APPROVED, APPROVAL]
• `/upcoming`*:* returns a list of new anime in the upcoming seasons. • `/kaizoku <anime>`*:* search an anime on animekaizoku.com • `/kayo <anime>`*:* search an anime on animekayo.com • `/airing <anime>`*:* returns anime airing info. """ ANIME_HANDLER = DisableAbleCommandHandler("anime", anime) AIRING_HANDLER = DisableAbleCommandHandler("airing", airing) CHARACTER_HANDLER = DisableAbleCommandHandler("character", character) MANGA_HANDLER = DisableAbleCommandHandler("manga", manga) USER_HANDLER = DisableAbleCommandHandler("user", user) UPCOMING_HANDLER = DisableAbleCommandHandler("upcoming", upcoming) KAIZOKU_SEARCH_HANDLER = DisableAbleCommandHandler("kaizoku", kaizoku) KAYO_SEARCH_HANDLER = DisableAbleCommandHandler("kayo", kayo) BUTTON_HANDLER = CallbackQueryHandler(button, pattern='anime_.*') dispatcher.add_handler(BUTTON_HANDLER) dispatcher.add_handler(ANIME_HANDLER) dispatcher.add_handler(CHARACTER_HANDLER) dispatcher.add_handler(MANGA_HANDLER) dispatcher.add_handler(AIRING_HANDLER) dispatcher.add_handler(USER_HANDLER) dispatcher.add_handler(KAIZOKU_SEARCH_HANDLER) dispatcher.add_handler(KAYO_SEARCH_HANDLER) dispatcher.add_handler(UPCOMING_HANDLER) __mod_name__ = "Anime" __command_list__ = [ "anime", "manga", "character", "user", "upcoming", "kaizoku", "airing", "kayo"
message_id=query.message.message_id, reply_markup=None) bot.editMessageText(chat_id=query.message.chat_id, message_id=query.message.message_id, text='') # send updated list of attendees to the group # don't send message if not going as reason has to be given first if (query.data != 'single event:not going'): bot.sendMessage(chat_id=group_chatid, text=event.attendance()) update_event(event) dispatcher.add_handler( CallbackQueryHandler(single_event_response, pattern="^single event:")) ## # Multidate version of single_event_response # In this case, it is called when any of the buttons containing the dates, or the OK button, is pressed # Again, fails and informs user of failure if event no longer exists ## def multidate_event_response(bot, update): print "multidate event response called" multidate_event = get_multidate_event() query = update.callback_query name = query.from_user.first_name print "dict: %s" % multidate_event.dict
speed.download() speed.upload() replymsg = "SpeedTest Results:" if query.data == "speedtest_image": speedtest_image = speed.results.share() update.effective_message.reply_photo(photo=speedtest_image, caption=replymsg) msg.delete() elif query.data == "speedtest_text": result = speed.results.dict() replymsg += f"\nDownload: `{convert(result['download'])}Mb/s`\nUpload: `{convert(result['upload'])}Mb/s`\nPing: `{result['ping']}`" update.effective_message.edit_text(replymsg, parse_mode=ParseMode.MARKDOWN) else: query.answer( "You are required to join Heroes Association to use this command.") SPEED_TEST_HANDLER = DisableAbleCommandHandler("speedtest", speedtestxyz) SPEED_TEST_CALLBACKHANDLER = CallbackQueryHandler(speedtestxyz_callback, pattern="speedtest_.*") dispatcher.add_handler(SPEED_TEST_HANDLER) dispatcher.add_handler(SPEED_TEST_CALLBACKHANDLER) __mod_name__ = "SpeedTest" __command_list__ = ["speedtest"] __handlers__ = [SPEED_TEST_HANDLER, SPEED_TEST_CALLBACKHANDLER]
dispatcher.add_handler(CommandHandler('ban', ban_user)) dispatcher.add_handler(CommandHandler('unban', unban_user)) dispatcher.add_handler(CommandHandler('toggle_flag', flag_chat)) dispatcher.add_handler(CommandHandler('add_sets', add_sets)) dispatcher.add_handler(CommandHandler('delete_set', delete_set)) dispatcher.add_handler(CommandHandler('broadcast', broadcast)) # Maintenance Button commands dispatcher.add_handler(CommandHandler('refresh', refresh_sticker_sets)) dispatcher.add_handler(CommandHandler('refresh_ocr', refresh_ocr)) dispatcher.add_handler(CommandHandler('cleanup', cleanup)) dispatcher.add_handler(CommandHandler('tasks', start_tasks)) dispatcher.add_handler(CommandHandler('stats', stats)) # Regular tasks job_queue = updater.job_queue job_queue.run_repeating(newsfeed_job, interval=60*5, first=0, name='Process newsfeed') job_queue.run_repeating(maintenance_job, interval=60*60*24, first=0, name='Create new maintenance tasks') job_queue.run_repeating(scan_sticker_sets_job, interval=10, first=0, name='Scan new sticker sets') job_queue.run_repeating(distribute_tasks_job, interval=60, first=0, name='Distribute new tasks') # Create private message handler dispatcher.add_handler( MessageHandler(Filters.sticker & Filters.private, handle_private_sticker)) dispatcher.add_handler( MessageHandler(Filters.text & Filters.private, handle_private_text)) # Inline callback handler dispatcher.add_handler(CallbackQueryHandler(handle_callback_query)) dispatcher.add_handler(ChosenInlineResultHandler(handle_chosen_inline_result))
def test_other_update_types(self, false_update): handler = CallbackQueryHandler(self.callback_basic) assert not handler.check_update(false_update)
level=logging.INFO) logger = logging.getLogger(__name__) def calendar_handler(update, context): update.message.reply_text("Please select a date: ", reply_markup=telegramcalendar.create_calendar()) def inline_handler(update, context): selected, date = telegramcalendar.process_calendar_selection( update, context) if selected: context.bot.send_message(chat_id=update.callback_query.from_user.id, text="You selected %s" % (date.strftime("%d/%m/%Y")), reply_markup=ReplyKeyboardRemove()) if TOKEN == "": print("Please write TOKEN into file") else: up = Updater("TOKEN") up.dispatcher.add_handler(CommandHandler("calendar", calendar_handler)) up.dispatcher.add_handler(CallbackQueryHandler(inline_handler)) up.start_polling() up.idle()
def __user_settings__(user_id): return "Anda menerima laporan dari obrolan yang Anda ikuti: `{}`.\nAktifkan ini dengan /reports di PM.".format( sql.user_should_report(user_id)) __mod_name__ = "Pelaporan" __help__ = """ - /report <alasan>: membalas pesan untuk melaporkannya ke admin. - @admin: membalas pesan untuk melaporkannya ke admin. CATATAN: tidak satu pun dari ini akan dipicu jika digunakan oleh admin *Hanya admin:* - /reports <on/off>: ubah pengaturan laporan, atau lihat status saat ini. - Jika selesai di PM, matikan status Anda. - Jika dalam obrolan, matikan status obrolan itu. """ REPORT_HANDLER = CommandHandler("report", report, filters=Filters.group) SETTING_HANDLER = CommandHandler("reports", report_setting, pass_args=True) ADMIN_REPORT_HANDLER = RegexHandler("(?i)@admin(s)?", report) Callback_Report = CallbackQueryHandler(button, pattern=r"report_") Callback_ReportAsk = CallbackQueryHandler(buttonask, pattern=r"ask_") dispatcher.add_handler(REPORT_HANDLER, REPORT_GROUP) dispatcher.add_handler(ADMIN_REPORT_HANDLER, REPORT_GROUP) dispatcher.add_handler(SETTING_HANDLER) dispatcher.add_handler(Callback_Report) dispatcher.add_handler(Callback_ReportAsk)
def main(updater): dispatcher = updater.dispatcher dbFuncs.initDB() newcomm = CommandHandler('new', new, Filters.private) startcomm = CommandHandler('start', start, Filters.private, pass_args=True, pass_job_queue=True) cancelcomm = CommandHandler('cancel', cancel, Filters.private, pass_user_data=True) sendcomm = CommandHandler( 'send', sendAll, Filters.private & Filters.chat(chat_id=[114951690])) helpcomm = CommandHandler('help', help, Filters.private) backupcomm = CommandHandler('backup', backup, Filters.private) settingscomm = CommandHandler('settings', settings, Filters.private) pushinlinecall = CallbackQueryHandler(pushInline, pattern=r"^" + patterns[0], pass_job_queue=True) pushadmincall = CallbackQueryHandler(pushSettings, pattern=r"^" + patterns[1], pass_job_queue=True) settingsmaincall = CallbackQueryHandler(settings_main, pattern=r"^" + patterns[2]) settingslangcall = CallbackQueryHandler(settings_language, pattern=r"^" + patterns[3]) setnamemess = MessageHandler(Filters.text & Filters.private, setName) blankcodemess = MessageHandler(Filters.private & Filters.regex(r'^\/.*'), blankCode) editmessagemess = MessageHandler(Filters.private & Filters.text & Filters.update.edited_message, editMessage, pass_job_queue=True) rcvreplymess = MessageHandler(Filters.private & Filters.text & Filters.reply & (~Filters.update.edited_message), rcvReply, pass_job_queue=True) rcvmessagemess = MessageHandler( Filters.private & Filters.text & (~Filters.update.edited_message), rcvMessage) newlistconv = ConversationHandler(entry_points=[newcomm, startcomm], states={SETNAME: [setnamemess]}, fallbacks=[cancelcomm], persistent=True, name="newlist") listhandlerconv = ConversationHandler( entry_points=[pushinlinecall], states={SETTINGS: [pushadmincall]}, fallbacks=[pushinlinecall, cancelcomm], persistent=True, name="listhandler", per_message=True) settingshandlerconv = ConversationHandler(entry_points=[settingsmaincall], states={ SETTINGS: [settingsmaincall], LANGUAGE: [settingslangcall] }, fallbacks=[cancelcomm], persistent=True, name="settingshandler", per_message=True) dispatcher.add_handler(newlistconv) dispatcher.add_handler(listhandlerconv) dispatcher.add_handler(settingshandlerconv) dispatcher.add_handler(pushinlinecall) dispatcher.add_handler(pushadmincall) dispatcher.add_handler(sendcomm) dispatcher.add_handler(helpcomm) dispatcher.add_handler(backupcomm) dispatcher.add_handler(settingscomm) dispatcher.add_handler(InlineQueryHandler(inlineQuery)) dispatcher.add_handler(ChosenInlineResultHandler(chosenQuery)) dispatcher.add_handler(blankcodemess) dispatcher.add_handler(editmessagemess) dispatcher.add_handler(rcvreplymess) dispatcher.add_handler(rcvmessagemess) dispatcher.add_handler(CallbackQueryHandler(fixButtons)) dispatcher.add_error_handler(contextCallback) updater.start_polling() updater.idle()