def get_user_id(username): # ensure valid userid if len(username) <= 5: return None if username.startswith("@"): username = username[1:] users = sql.get_userid_by_name(username) if not users: return None elif len(users) == 1: return users[0].user_id else: for user_obj in users: try: userdat = dispatcher.bot.get_chat(user_obj.user_id) if userdat.username == username: return userdat.id except BadRequest as excp: if excp.message == "Chat not found": pass else: LOGGER.exception("Error extracting user ID") return None
async def song(client, message): chat_id = message.chat.id user_id = message.from_user["id"] add_chat_to_db(str(chat_id)) args = get_arg(message) + " " + "song" if args.startswith(" "): await message.reply("Enter a song name. Check /help") return "" status = await message.reply("Processing...") video_link = yt_search(args) if not video_link: await status.edit("Song not found.") return "" yt = YouTube(video_link) audio = yt.streams.filter(only_audio=True).first() try: download = audio.download(filename=f"{str(user_id)}") except Exception as ex: await status.edit("Failed to download song") LOGGER.error(ex) return "" rename = os.rename(download, f"{str(user_id)}.mp3") await app.send_chat_action(message.chat.id, "upload_audio") await app.send_audio( chat_id=message.chat.id, audio=f"{str(user_id)}.mp3", duration=int(yt.length), title=str(yt.title), performer=str(yt.author), reply_to_message_id=message.message_id, ) await status.delete() os.remove(f"{str(user_id)}.mp3")
async def s(client, message): chat_id = message.chat.id user_id = message.from_user["id"] args = get_arg(message) + " " + "song" if args.startswith(" "): await message.reply("Enter a song name. Check /help") return "" status = await message.reply("Rukja Bsdk....") video_link = yt_search(args) if not video_link: await status.edit("Song not found.") return "" yt = YouTube(video_link) audio = yt.streams.filter(only_audio=True).first() try: download = audio.download(filename=f"{str(user_id)}") except Exception as ex: await status.edit("Failed to download song") LOGGER.error(ex) return "" rename = os.rename(download, f"{str(user_id)}.mp3") await app.send_chat_action(message.chat.id, "upload_audio") await app.send_audio( chat_id=message.chat.id, audio=f"{str(user_id)}.mp3", duration=int(yt.length), thumb=f"https://telegra.ph/file/96c37616e91e501292040.jpg", caption="**Uploaded By @SushantGirdhar**", title=str(yt.title), performer=str(yt.author), reply_to_message_id=message.message_id, ) await status.delete() os.remove(f"{str(user_id)}.mp3")
def help_button(update, context): query = update.callback_query mod_match = re.match(r"help_module\((.+?)\)", query.data) prev_match = re.match(r"help_prev\((.+?)\)", query.data) next_match = re.match(r"help_next\((.+?)\)", query.data) back_match = re.match(r"help_back", query.data) print(query.message.chat.id) try: if mod_match: module = mod_match.group(1) text = ( "Here is the help for the *{}* module:\n".format( HELPABLE[module].__mod_name__ ) + HELPABLE[module].__help__ ) query.message.edit_text(text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( [[InlineKeyboardButton(text="⬅️ Back", callback_data="help_back")]] ), ) elif prev_match: curr_page = int(prev_match.group(1)) query.message.edit_text( text=HELP_STRINGS, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules(curr_page - 1, HELPABLE, "help"))) elif next_match: next_page = int(next_match.group(1)) query.message.edit_text( text=HELP_STRINGS, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules(next_page + 1, HELPABLE, "help"))) elif back_match: query.message.edit_text( text=HELP_STRINGS, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(paginate_modules(0, HELPABLE, "help"))) # ensure no spinny white circle context.bot.answer_callback_query(query.id) except Exception as excp: if excp.message not in { "Message is not modified", "Query_id_invalid", "Message can't be deleted", }: query.message.edit_text(excp.message) LOGGER.exception("Exception in help buttons. %s", str(query.data))
def error_handler(update, context): """Log the error and send a telegram message to notify the developer.""" cmd, args = update.effective_message.text.split(None, 1) LOGGER.error(msg="Error found, check dump below:", exc_info=context.error) # traceback.format_exception returns the usual python message about an exception, but as a # list of strings rather than a single string, so we have to join them together. tb_list = traceback.format_exception(None, context.error, context.error.__traceback__) trace = "".join(tb_list) # lets try to get as much information from the telegram update as possible payload = f"\n<b>- Command</b>: <code>{cmd}</code>" payload += f"\n<b>- Arguments</b>: <code>{args}</code>" payload += f"\n<b>- Error message</b>:\n<code>{context.error}</code>" # normally, we always have a user. If not, its either a channel or a poll update. if update.effective_user: payload += f" \n<b>- User</b>: {mention_html(update.effective_user.id, update.effective_user.first_name)}" # there are more situations when you don't get a chat if update.effective_chat: if update.effective_chat.title == None: payload += f" \n<b>- Chat</b>: <i>Bot PM</i>" else: payload += ( f" \n<b>- Chat</b>: <i>{update.effective_chat.title}</i>") # but only one where you have an empty payload by now: A poll (buuuh) if update.poll: payload += f" \n<b>- Poll id</b>: {update.poll.id}." # lets put this in a "well" formatted text text = f"<b>Error found while handling an update!</b> {payload}" # now paste the error (trace) in nekobin and make buttons # with url of log, as log in telegram message is hardly readable.. key = (requests.post( "https://nekobin.com/api/documents", json={ "content": f"{trace}\n\n{json.dumps(update.to_dict(), indent=2, ensure_ascii=False)}" }, ).json().get("result").get("key")) markup = InlineKeyboardMarkup([[ InlineKeyboardButton( text="Full traceback on nekobin", url=f"https://nekobin.com/{key}.py", ), # InlineKeyboardButton( # text="Send traceback as message", # , # ), ]]) context.bot.send_message(OWNER_ID, text, reply_markup=markup, parse_mode="html")
def broadcast(update, context): to_send = update.effective_message.text.split(None, 1) if len(to_send) >= 2: chats = sql.get_all_chats() or [] failed = 0 for chat in chats: try: context.bot.sendMessage(int(chat.chat_id), to_send[1]) sleep(0.1) except TelegramError: failed += 1 LOGGER.warning( "Couldn't send broadcast to %s, group name %s", str(chat.chat_id), str(chat.chat_name), ) update.effective_message.reply_text( "Broadcast complete. {} groups failed to receive the message, probably " "due to being kicked.".format(failed))
Ketik /help untuk menampilkan semua perintah! """ keyboard = [[ InlineKeyboardButton("Maintained by", url="t.me/LoliKillers"), InlineKeyboardButton("Help", callback_data="help"), ]] if update.effective_chat.type == "private": args = context.args update.effective_message.reply_photo( "https://telegra.ph/file/981f776678ac4980d39fd.png", PM_START_TEXT, timeout=60, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup(keyboard), ) else: update.effective_message.reply_text("Ohayooo!") def main(): dispatcher.add_handler(CommandHandler("start", start)) if __name__ == "__main__": LOGGER.info("Using long polling.") main() updater.start_polling(timeout=15, read_latency=4) updater.idle()
user_id = message.from_user["id"] name = message.from_user["first_name"] if message.chat.type == "private": btn = InlineKeyboardMarkup( [ [ InlineKeyboardButton( text="🗣Add me to your group", url="https://t.me/SongAnie_bot?startgroup=true" ) ] ] ) else: btn = None await message.reply(start_text.format(name, user_id), reply_markup=btn) add_chat_to_db(str(chat_id)) @app.on_message(filters.create(ignore_blacklisted_users) & filters.command("help")) async def help(client, message): if message.from_user["id"] == OWNER_ID: await message.reply(owner_help) return "" text = "Syntax: /song song name" await message.reply(text) app.start() LOGGER.info("Your bot is now online.") idle()
module = args[1].lower() text = ("Here is the available help for the *{}* module:\n".format( HELPABLE[module].__mod_name__) + HELPABLE[module].__help__) send_help( chat.id, text, InlineKeyboardMarkup([[ InlineKeyboardButton(text="Back", callback_data="help_back") ]]), ) else: send_help(chat.id, HELP_STRINGS) def main(): dispatcher.add_handler(CommandHandler("start", start, pass_args=True)) help_handler = CommandHandler("help", get_help) help_callback_handler = CallbackQueryHandler(help_button, pattern=r"help_") dispatcher.add_handler(help_handler) dispatcher.add_handler(help_callback_handler) dispatcher.add_error_handler(error_handler) if __name__ == "__main__": LOGGER.info("Successfully loaded modules: " + str(ALL_MODULES)) LOGGER.info("Using long polling.") main() updater.start_polling(timeout=15, read_latency=4) updater.idle()