def de_json(data): data = super(InlineKeyboardMarkup, InlineKeyboardMarkup).de_json(data) if not data: return None data['inline_keyboard'] = [InlineKeyboardButton.de_list(inline_keyboard) for inline_keyboard in data['inline_keyboard']] return InlineKeyboardMarkup(**data)
def de_json(cls, data, bot): data = super(InlineKeyboardMarkup, cls).de_json(data, bot) if not data: return None data['inline_keyboard'] = [ InlineKeyboardButton.de_list(inline_keyboard, bot) for inline_keyboard in data['inline_keyboard'] ] return cls(**data)
def de_json(data, bot): """ Args: data (dict): bot (telegram.Bot): Returns: telegram.InlineKeyboardMarkup: """ data = super(InlineKeyboardMarkup, InlineKeyboardMarkup).de_json(data, bot) if not data: return None data['inline_keyboard'] = [InlineKeyboardButton.de_list(inline_keyboard, bot) for inline_keyboard in data['inline_keyboard']] return InlineKeyboardMarkup(**data)
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler import logging from f_gpio import * from secret import * ## inizio impostazioni allowedUsers = getAllowedUsers() token = getToken() ## fine impostazioni # variabili globali stanza = "" locationPickerKeyboard = [[ InlineKeyboardButton("Sala 🛋️", callback_data="s"), InlineKeyboardButton("Cucina 🔪", callback_data="c") ], [ InlineKeyboardButton("Camera Fabio 💻", callback_data="cf"), InlineKeyboardButton("Camera Sonia 🛏️", callback_data="cs") ], [InlineKeyboardButton("Tutto 🏠", callback_data='t')]] upDownKeyboard = [[InlineKeyboardButton("Sù 🔺", callback_data="u")], [InlineKeyboardButton("A metà 🔴", callback_data="m")], [InlineKeyboardButton("Giù 🔻", callback_data="d")]] logging.basicConfig(
def settings_button(bot: Bot, update: Update): query = update.callback_query user = update.effective_user mod_match = re.match(r"stngs_module\((.+?),(.+?)\)", query.data) prev_match = re.match(r"stngs_prev\((.+?),(.+?)\)", query.data) next_match = re.match(r"stngs_next\((.+?),(.+?)\)", query.data) back_match = re.match(r"stngs_back\((.+?)\)", query.data) try: if mod_match: chat_id = mod_match.group(1) module = mod_match.group(2) chat = bot.get_chat(chat_id) text = "*{}* has the following settings for the *{}* module:\n\n".format(escape_markdown(chat.title), CHAT_SETTINGS[module].__mod_name__) + \ CHAT_SETTINGS[module].__chat_settings__(chat_id, user.id) query.message.reply_text( text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text="Back", callback_data="stngs_back({})".format(chat_id)) ]])) elif prev_match: chat_id = prev_match.group(1) curr_page = int(prev_match.group(2)) chat = bot.get_chat(chat_id) query.message.reply_text( "Hi there! There are quite a few settings for {} - go ahead and pick what " "you're interested in.".format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(curr_page - 1, CHAT_SETTINGS, "stngs", chat=chat_id))) elif next_match: chat_id = next_match.group(1) next_page = int(next_match.group(2)) chat = bot.get_chat(chat_id) query.message.reply_text( "Hi there! There are quite a few settings for {} - go ahead and pick what " "you're interested in.".format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(next_page + 1, CHAT_SETTINGS, "stngs", chat=chat_id))) elif back_match: chat_id = back_match.group(1) chat = bot.get_chat(chat_id) query.message.reply_text( text= "Hi there! There are quite a few settings for {} - go ahead and pick what " "you're interested in.".format(escape_markdown(chat.title)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules(0, CHAT_SETTINGS, "stngs", chat=chat_id))) # ensure no spinny white circle bot.answer_callback_query(query.id) query.message.delete() except BadRequest as excp: if excp.message == "Message is not modified": pass elif excp.message == "Query_id_invalid": pass elif excp.message == "Message can't be deleted": pass else: LOGGER.exception("Exception in settings buttons. %s", str(query.data))
def new_member(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] msg = update.effective_message # type: Optional[Message] chat_name = chat.title or chat.first or chat.username # type: Optional:[chat name] should_welc, cust_welcome, welc_type = sql.get_welc_pref(chat.id) welc_mutes = sql.welcome_mutes(chat.id) casPrefs = sql.get_cas_status(str(chat.id)) #check if enabled, obviously autoban = sql.get_cas_autoban(str(chat.id)) chatbanned = sql.isBanned(str(chat.id)) defense = sql.getDefenseStatus(str(chat.id)) time_value = sql.getKickTime(str(chat.id)) fed_id = feds_sql.get_fed_id(chat.id) fed_info = feds_sql.get_fed_info(fed_id) fban, fbanreason, fbantime = feds_sql.get_fban_user(fed_id, user.id) if chatbanned: bot.leave_chat(int(chat.id)) elif fban: update.effective_message.reply_text( "🔨 User {} is banned in the current Federation ({}), and so has been Removed.\n<b>Reason</b>: {}" .format(mention_html(user.id, user.first_name), fed_info['fname'], fbanreason or "No reason given"), parse_mode=ParseMode.HTML) bot.kick_chat_member(chat.id, user.id) #elif casPrefs and not autoban and cas.banchecker(user.id): # bot.restrict_chat_member(chat.id, user.id, # can_send_messages=False, # can_send_media_messages=False, # can_send_other_messages=False, # can_add_web_page_previews=False) #msg.reply_text("Warning! This user is CAS Banned. I have muted them to avoid spam. Ban is advised.") #isUserGbanned = gbansql.is_user_gbanned(user.id) #if not isUserGbanned: #report = "CAS Banned user detected: <code>{}</code>".format(user.id) #send_to_list(bot, SUDO_USERS + SUPPORT_USERS, report, html=True) #if defense: # bantime = int(time.time()) + 60 # chat.kick_member(new_mem.id, until_date=bantime) #elif casPrefs and autoban and cas.banchecker(user.id): # chat.kick_member(user.id) #msg.reply_text("CAS banned user detected! User has been automatically banned!") # isUserGbanned = gbansql.is_user_gbanned(user.id) #if not isUserGbanned: #report = "CAS Banned user detected: <code>{}</code>".format(user.id) #send_to_list(bot, SUDO_USERS + SUPPORT_USERS, report, html=True) #elif defense and (user.id not in SUDO_USERS + SUPPORT_USERS): # bantime = int(time.time()) + 60 # chat.kick_member(user.id, until_date=bantime) elif should_welc: sent = None new_members = update.effective_message.new_chat_members for new_mem in new_members: # Give the owner a special welcome if new_mem.id == OWNER_ID: update.effective_message.reply_text( "Oh🤴Genos,My Owner has just joined your group.") continue # Welcome Devs elif new_mem.id in DEV_USERS: update.effective_message.reply_text( "Whoa! A member of the Heroes Association just joined!") # Welcome Sudos elif new_mem.id in SUDO_USERS: update.effective_message.reply_text( "Huh! A Sudo User just joined! Stay Alert!") # Welcome Support elif new_mem.id in SUPPORT_USERS: update.effective_message.reply_text( "Huh! Someone with a Support User just joined!") # Welcome Whitelisted elif new_mem.id in WHITELIST_USERS: update.effective_message.reply_text( "Oof! A Whitelist User just joined!") elif new_mem.id == 920437078: update.effective_message.reply_text( "Oh🤴Genos,My Creator/Developer has just joined your group." ) # Make bot greet admins elif new_mem.id == bot.id: update.effective_message.reply_text( "Hey {}, I'm {}! Thank you for adding me to {}" " and be sure to check /help in PM for more commands and tricks!" .format(user.first_name, bot.first_name, chat_name)) bot.send_message( MESSAGE_DUMP, "I have been added to {} with \nID: <pre>{}</pre>".format( chat.title, chat.id), parse_mode=ParseMode.HTML) else: # If welcome message is media, send with appropriate function if welc_type != sql.Types.TEXT and welc_type != sql.Types.BUTTON_TEXT: ENUM_FUNC_MAP[welc_type](chat.id, cust_welcome) return # else, move on first_name = new_mem.first_name or "PersonWithNoName" # edge case of empty name - occurs for some bugs. if cust_welcome: if new_mem.last_name: fullname = "{} {}".format(first_name, new_mem.last_name) else: fullname = first_name count = chat.get_members_count() mention = mention_markdown(new_mem.id, first_name) if new_mem.username: username = "******" + escape_markdown(new_mem.username) else: username = mention valid_format = escape_invalid_curly_brackets( cust_welcome, VALID_WELCOME_FORMATTERS) res = valid_format.format( first=escape_markdown(first_name), last=escape_markdown(new_mem.last_name or first_name), fullname=escape_markdown(fullname), username=username, mention=mention, count=count, chatname=escape_markdown(chat.title), id=new_mem.id) buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard(buttons) else: res = sql.DEFAULT_WELCOME.format(first=first_name, chatname=chat.title) keyb = [] keyboard = InlineKeyboardMarkup(keyb) sent = send( update, res, keyboard, sql.DEFAULT_WELCOME.format( first=first_name, chatname=chat.title)) # type: Optional[Message] #Sudo user exception from mutes: if is_user_ban_protected(chat, new_mem.id, chat.get_member(new_mem.id)): continue #Safe mode newMember = chat.get_member(int(new_mem.id)) if welc_mutes == "on" and ((newMember.can_send_messages is None or newMember.can_send_messages)): buttonMsg = msg.reply_text( "Click the button below to prove you're human", reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text="I'm not a bot! 🤖", callback_data="userverify_({})".format( new_mem.id)) ]])) bot.restrict_chat_member(chat.id, new_mem.id, can_send_messages=False, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False) delete_join(bot, update) prev_welc = sql.get_clean_pref(chat.id) if prev_welc: try: bot.delete_message(chat.id, prev_welc) except BadRequest as excp: pass if sent: sql.set_clean_welcome(chat.id, sent.message_id)
class TestInlineQueryResultCachedPhoto: id_ = 'id' type_ = 'photo' photo_file_id = 'photo file id' title = 'title' description = 'description' caption = 'caption' parse_mode = 'HTML' caption_entities = [MessageEntity(MessageEntity.ITALIC, 0, 7)] input_message_content = InputTextMessageContent('input_message_content') reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]]) def test_expected_values(self, inline_query_result_cached_photo): assert inline_query_result_cached_photo.type == self.type_ assert inline_query_result_cached_photo.id == self.id_ assert inline_query_result_cached_photo.photo_file_id == self.photo_file_id assert inline_query_result_cached_photo.title == self.title assert inline_query_result_cached_photo.description == self.description assert inline_query_result_cached_photo.caption == self.caption assert inline_query_result_cached_photo.parse_mode == self.parse_mode assert inline_query_result_cached_photo.caption_entities == self.caption_entities assert ( inline_query_result_cached_photo.input_message_content.to_dict() == self.input_message_content.to_dict() ) assert ( inline_query_result_cached_photo.reply_markup.to_dict() == self.reply_markup.to_dict() ) def test_to_dict(self, inline_query_result_cached_photo): inline_query_result_cached_photo_dict = inline_query_result_cached_photo.to_dict() assert isinstance(inline_query_result_cached_photo_dict, dict) assert ( inline_query_result_cached_photo_dict['type'] == inline_query_result_cached_photo.type ) assert inline_query_result_cached_photo_dict['id'] == inline_query_result_cached_photo.id assert ( inline_query_result_cached_photo_dict['photo_file_id'] == inline_query_result_cached_photo.photo_file_id ) assert ( inline_query_result_cached_photo_dict['title'] == inline_query_result_cached_photo.title ) assert ( inline_query_result_cached_photo_dict['description'] == inline_query_result_cached_photo.description ) assert ( inline_query_result_cached_photo_dict['caption'] == inline_query_result_cached_photo.caption ) assert ( inline_query_result_cached_photo_dict['parse_mode'] == inline_query_result_cached_photo.parse_mode ) assert inline_query_result_cached_photo_dict['caption_entities'] == [ ce.to_dict() for ce in inline_query_result_cached_photo.caption_entities ] assert ( inline_query_result_cached_photo_dict['input_message_content'] == inline_query_result_cached_photo.input_message_content.to_dict() ) assert ( inline_query_result_cached_photo_dict['reply_markup'] == inline_query_result_cached_photo.reply_markup.to_dict() ) def test_equality(self): a = InlineQueryResultCachedPhoto(self.id_, self.photo_file_id) b = InlineQueryResultCachedPhoto(self.id_, self.photo_file_id) c = InlineQueryResultCachedPhoto(self.id_, '') d = InlineQueryResultCachedPhoto('', self.photo_file_id) e = InlineQueryResultCachedVoice(self.id_, '', '') assert a == b assert hash(a) == hash(b) assert a is not b assert a == c assert hash(a) == hash(c) assert a != d assert hash(a) != hash(d) assert a != e assert hash(a) != hash(e)
def reply_handler(bot, update): text = update.message.text main_message = bot.sendMessage(chat_id=update.message.chat.id, text="正在試試看這東西\n\nTrying this.").message_id print(text) try: n = requests.get(text) except: bot.editMessageText(chat_id=update.message.chat.id, message_id=main_message, text="無效網址\n\nInvalid URL") return #print(n.text) all_stickers = find_sticker_sites(n.text) if len(all_stickers) != 0: print(len(all_stickers)) # temp = text.find("product") # if temp!=-1: # temp = text[temp+8:] # else: # temp = text.find("sticker") # temp = text[temp+8:] # sticker_number = temp[:temp.find("/")] sticker_number = findStickerNumInUrl(all_stickers[0]) title = find_ex( find_ex(n.text, "head"), "title" )[6:find_ex(find_ex(n.text, "head"), "title")[:].find("LINE") - 2].replace("&", "&") #Check if sticker exist try: a = bot.getStickerSet(name="line" + str(sticker_number) + "_by_RekcitsEnilbot") a_len = len(a.stickers) status = 1 except: a = 0 a_len = 0 status = -1 if status == 1: if len(a.stickers) != len(all_stickers): bot.editMessageText(chat_id=update.message.chat.id, message_id=main_message, text="貼圖包更新\n\nUpdate the sticker set.") else: bot.editMessageText(chat_id=update.message.chat.id, message_id=main_message, text="總算找到了\nThis one?!" + "\n\nLine sticker number:" + str(sticker_number)) bot.sendSticker( chat_id=update.message.chat.id, sticker=a.stickers[0].file_id, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton(text=title, url="https://t.me/addstickers/" + "line" + str(sticker_number) + "_by_RekcitsEnilbot") ]])) return temp_message = title + "\n發現" + str( len(all_stickers)) + "張貼圖\n\nFound " + str( len(all_stickers)) + " stickers\n" temp_message2 = temp_message for i in range(len(all_stickers)): temp_message2 += "_" temp_message2 += "0/" + str(len(all_stickers)) bot.editMessageText(chat_id=update.message.chat.id, message_id=main_message, text=temp_message2) main_handle(sticker_number, update.message.chat.id, main_message, all_stickers, title) else: all_stickers = find_message_sticker_sites(n.text) print(len(all_stickers)) if len(all_stickers) == 0: bot.editMessageText( chat_id=update.message.chat.id, message_id=main_message, text="沒有找到任何Line貼圖?!\n\nCan't find any line sticker?!") return sticker_number = findStickerNumInUrl(all_stickers[0][0]) print(sticker_number) title = find_ex( find_ex(n.text, "head"), "title" )[6:find_ex(find_ex(n.text, "head"), "title")[:].find("LINE") - 2].replace("&", "&") #Check if sticker exist try: a = bot.getStickerSet(name="line" + str(sticker_number) + "_by_RekcitsEnilbot") a_len = len(a.stickers) status = 1 except: a = 0 a_len = 0 status = -1 if status == 1: if len(a.stickers) != len(all_stickers): bot.editMessageText(chat_id=update.message.chat.id, message_id=main_message, text="貼圖包更新\n\nUpdate the sticker set.") else: bot.editMessageText(chat_id=update.message.chat.id, message_id=main_message, text="總算找到了\nThis one?!" + "\n\nLine sticker number:" + str(sticker_number)) bot.sendSticker( chat_id=update.message.chat.id, sticker=a.stickers[0].file_id, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton(text=title, url="https://t.me/addstickers/" + "line" + str(sticker_number) + "_by_RekcitsEnilbot") ]])) return temp_message = title + "\n發現" + str( len(all_stickers)) + "張貼圖\n\nFound " + str( len(all_stickers)) + " stickers\n" temp_message2 = temp_message for i in range(len(all_stickers)): temp_message2 += "_" temp_message2 += "0/" + str(len(all_stickers)) bot.editMessageText(chat_id=update.message.chat.id, message_id=main_message, text=temp_message2) main_handle_for_message_sticker(sticker_number, update.message.chat.id, main_message, all_stickers, title)
def generar_markup(self, update, context): opciones = [[InlineKeyboardButton(" ", callback_data="{}".format(i)) for i in j] for j in [[0, 1, 2], [3, 4, 5], [6, 7, 8]]] return InlineKeyboardMarkup(opciones)
def warn(user: User, chat: Chat, reason: str, message: Message, warner: User = None) -> str: if is_user_admin(chat, user.id): # message.reply_text("Damn admins, They are too far to be One Punched!") return if user.id in TIGER_USERS: if warner: message.reply_text("Tigers cant be warned.") else: message.reply_text( "Tiger triggered an auto warn filter!\n I can't warn tigers but they should avoid abusing this." ) return if user.id in WHITELIST_USERS: if warner: message.reply_text("Wolf disasters are warn immune.") else: message.reply_text( "Wolf Disaster triggered an auto warn filter!\nI can't warn wolves but they should avoid abusing this." ) return if warner: warner_tag = mention_html(warner.id, warner.first_name) else: warner_tag = "Automated warn filter." limit, soft_warn = sql.get_warn_setting(chat.id) num_warns, reasons = sql.warn_user(user.id, chat.id, reason) if num_warns >= limit: sql.reset_warns(user.id, chat.id) if soft_warn: # punch chat.unban_member(user.id) reply = f"{limit} warnings, *Punches {mention_html(user.id, user.first_name)} with a normal punch!* " else: # ban chat.kick_member(user.id) reply = f"{limit} warnings, *Punches {mention_html(user.id, user.first_name)} with a Serious Punch* " for warn_reason in reasons: reply += f"\n - {html.escape(warn_reason)}" message.bot.send_sticker(chat.id, BAN_STICKER) # suzukabot's sticker keyboard = [] log_reason = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#WARN_BAN\n" f"<b>Admin:</b> {warner_tag}\n" f"<b>User:</b> {mention_html(user.id, user.first_name)}\n" f"<b>Reason:</b> {reason}\n" f"<b>Counts:</b> <code>{num_warns}/{limit}</code>") else: keyboard = InlineKeyboardMarkup([{ InlineKeyboardButton("Remove warn", callback_data="rm_warn({})".format(user.id)) }]) reply = f"{mention_html(user.id, user.first_name)} has {num_warns}/{limit} warnings... watch out!" if reason: reply += f"\nReason for last warn:\n{html.escape(reason)}" log_reason = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#WARN\n" f"<b>Admin:</b> {warner_tag}\n" f"<b>User:</b> {mention_html(user.id, user.first_name)}\n" f"<b>Reason:</b> {reason}\n" f"<b>Counts:</b> <code>{num_warns}/{limit}</code>") try: message.reply_text(reply, reply_markup=keyboard, parse_mode=ParseMode.HTML) except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text(reply, reply_markup=keyboard, parse_mode=ParseMode.HTML, quote=False) else: raise return log_reason
def menu(self, update:telegram.Update): try: message = _("Please select a {}".format(self.name)) replies = [] start = self.get_run('sf-start', 0, insert=True) real_start = start * self.offset real_end = real_start + self.offset for row in self.choices[real_start:real_end]: if isinstance(row, tuple): text, value = row elif isinstance(row, Model): text = str(row) value = str(row.id) else: text = value = row if self.multiple: if value in self.selected: text += " ✅" else: if value == self.selected: text += " ✅" replies.append([InlineKeyboardButton(_(text), callback_data="value::{}".format(value))]) row = [] if start > 0: row.append(InlineKeyboardButton(_("⏪"), callback_data="nav::{}".format(start-1))) all_pages = len(self.choices) // self.offset rest = len(self.choices) % self.offset range_max = min([all_pages, start+3]) inside = [] for page in range(start+1, range_max+1): inside.append(page) avail = 3 - len(inside) if avail: for page in range(start-avail, start): if page < 0: continue inside.append(page) inside = sorted(inside) for page in inside: row.append(InlineKeyboardButton(_("{}".format(page+1)), callback_data='nav::{}'.format(page))) if start > all_pages: pass elif start == all_pages and rest!=0: pass else: row.append(InlineKeyboardButton(_("⏩"), callback_data="nav::{}".format(start+1))) replies.append(row) replies.append([InlineKeyboardButton(_("OK"), callback_data="ok::ok"), InlineKeyboardButton(_("Cancel"), callback_data="cancel::cancel")]) kbd = InlineKeyboardMarkup(replies) return InputResponse(InputResponse.CONTINUE, MenuResponse(message, kbd), None) except Exception as e: logger.exception(str(e))
from telegram import InlineKeyboardMarkup, InlineKeyboardButton from constants import PRICES keyboard = [ [InlineKeyboardButton( text='Спасибо, я пока тут осмотрюсь...', # url='https://card.tochka.com/cjgbrgtye-individualnaia_konsultatsiia', callback_data='Не покупаем подписку' )], [ InlineKeyboardButton(f'1 месяц ({PRICES[1]} ₽)', callback_data=PRICES[1]), InlineKeyboardButton(f'3 месяца ({PRICES[3]} ₽)', callback_data=PRICES[3]), InlineKeyboardButton(f'Полгода ({PRICES[6]} ₽)', callback_data=PRICES[6]), ], [InlineKeyboardButton(f'Год ({PRICES[12]} ₽)', callback_data=PRICES[12])], ] payment_keyboard = InlineKeyboardMarkup(keyboard)
def command_regras(bot, update): cid = update.message.chat_id btn = [[InlineKeyboardButton("Rules", url="http://www.secrethitler.com/assets/Secret_Hitler_Rules.pdf")]] rulesMarkup = InlineKeyboardMarkup(btn) bot.send_message(cid, "Leia as regras oficiais do Secret Hitler:", reply_markup=rulesMarkup)
def settings_button(bot: Bot, update: Update): query = update.callback_query user = update.effective_user mod_match = re.match(r"stngs_module\((.+?),(.+?)\)", query.data) prev_match = re.match(r"stngs_prev\((.+?),(.+?)\)", query.data) next_match = re.match(r"stngs_next\((.+?),(.+?)\)", query.data) back_match = re.match(r"stngs_back\((.+?)\)", query.data) try: if mod_match: chat_id = mod_match.group(1) module = mod_match.group(2) chat = bot.get_chat(chat_id) getstatusadmin = bot.get_chat_member(chat_id, user.id) isadmin = getstatusadmin.status in ('administrator', 'creator') if isadmin == False or user.id != OWNER_ID: query.message.edit_text("Status admin anda telah berubah") return text = "*{}* memiliki pengaturan berikut untuk modul *{}*:\n\n".format(escape_markdown(chat.title), CHAT_SETTINGS[ module].__mod_name__) + \ CHAT_SETTINGS[module].__chat_settings__(chat_id, user.id) try: set_button = CHAT_SETTINGS[module].__chat_settings_btn__( chat_id, user.id) except AttributeError: set_button = [] set_button.append([ InlineKeyboardButton( text="Kembali", callback_data="stngs_back({})".format(chat_id)) ]) query.message.edit_text( text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(set_button)) elif prev_match: chat_id = prev_match.group(1) curr_page = int(prev_match.group(2)) chat = bot.get_chat(chat_id) query.message.edit_text( text= "Hai! Ada beberapa pengaturan untuk {} - lanjutkan dan pilih " "apa yang Anda minati.".format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(curr_page - 1, CHAT_SETTINGS, "stngs", chat=chat_id))) elif next_match: chat_id = next_match.group(1) next_page = int(next_match.group(2)) chat = bot.get_chat(chat_id) query.message.edit_text( text= "Hai! Ada beberapa pengaturan untuk {} - lanjutkan dan pilih " "apa yang Anda minati.".format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(next_page + 1, CHAT_SETTINGS, "stngs", chat=chat_id))) elif back_match: chat_id = back_match.group(1) chat = bot.get_chat(chat_id) query.message.edit_text( text= "Hai! Ada beberapa pengaturan untuk {} - lanjutkan dan pilih " "apa yang Anda minati.".format(escape_markdown(chat.title)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules(0, CHAT_SETTINGS, "stngs", chat=chat_id))) # ensure no spinny white circle bot.answer_callback_query(query.id) except Exception as excp: if excp.message == "Message is not modified": pass elif excp.message == "Query_id_invalid": pass elif excp.message == "Message can't be deleted": pass else: query.message.edit_text(excp.message) LOGGER.exception("Exception in settings buttons. %s", str(query.data))
def button(update, context): global bot_message try: query = update.callback_query query_dic = literal_eval(str(query)) button_chat_id = query_dic["message"]["chat"]["id"] button_message_id = query_dic["message"]["message_id"] button_clicker_id = query_dic["from"]["id"] button_clicker_username = the_username(query_dic) if button_chat_id in the_bot and button_clicker_id in the_bot[ button_chat_id]: if query.data == "ADD": mess = query.edit_message_text( text= f"{button_clicker_username} To add new massage please reply to the message" ) the_bot[button_chat_id][button_clicker_id] = { "state": "ADD", "random message": 0, "message_id": mess["message_id"], "username": button_clicker_username, } elif query.data == "DELETE": mess = query.edit_message_text( text= f"{button_clicker_username} To delete any message please reply to the message" ) the_bot[button_chat_id][button_clicker_id] = { "state": "DELETE", "random message": 0, "message_id": mess["message_id"], "username": button_clicker_username, } elif query.data == "STOP": context.bot.delete_message( chat_id=button_chat_id, message_id=the_bot[button_chat_id][button_clicker_id] ["message_id"], ) context.bot.send_message( chat_id=button_chat_id, text= f"{button_clicker_username} you lost the access to the bot now", ) the_bot[button_chat_id].pop(button_clicker_id) if the_bot[button_chat_id] == {}: the_bot.pop(button_chat_id) else: the_users = the_bot[button_chat_id].keys() reply_markup = InlineKeyboardMarkup(keyboard4) for i in the_users: context.bot.send_message( chat_id=button_chat_id, text= f'{the_bot[button_chat_id][i]["username"]} still has access to the bot ', reply_markup=reply_markup, ) elif query.data == "RANDOM": context.bot.delete_message( chat_id=button_chat_id, message_id=the_bot[button_chat_id][button_clicker_id] ["message_id"], ) while True: try: chat_id_in_firebase = (db.child("all_message").child( str(button_chat_id)).shallow().get()) messages_in_chat_id_in_firebase = list( chat_id_in_firebase.val()) the_random_key = random.randint( 0, len(messages_in_chat_id_in_firebase) - 1) the_message_in_firebase = messages_in_chat_id_in_firebase[ the_random_key] random_message = (db.child("all_message").child( str(button_chat_id)).child( str(the_message_in_firebase)).get()) info_of_random_message = dict(random_message.val()) keyboard5 = [ [ InlineKeyboardButton("Add New Massage", callback_data="ADD") ], [ InlineKeyboardButton("Delete a Message", callback_data="DELETE") ], [ InlineKeyboardButton( "Send a Random Message", callback_data="RANDOM", ) ], [ InlineKeyboardButton("Stop The Bot", callback_data="STOP") ], [ InlineKeyboardButton( "Delete the Random Message", callback_data="DELETE THIS", ) ], ] reply_markup = InlineKeyboardMarkup(keyboard5) context.bot.send_message( chat_id=button_chat_id, text= f'"{the_username(info_of_random_message)}" save this message\n' f"with caption \"{info_of_random_message['text']}\" \nat {datetime.fromtimestamp(info_of_random_message['date'])}", reply_to_message_id=the_message_in_firebase, ) mess = context.bot.send_message( chat_id=button_chat_id, text="Please choose what you want :", reply_markup=reply_markup, ) the_bot[button_chat_id][button_clicker_id] = { "state": "RANDOM", "random message": the_message_in_firebase, "message_id": mess["message_id"], "username": button_clicker_username, } break except TypeError: reply_markup = InlineKeyboardMarkup(keyboard2) mess = context.bot.send_message( chat_id=button_chat_id, text="I don't have any massage please add some", reply_markup=reply_markup, ) the_bot[button_chat_id][button_clicker_id] = { "state": "Nothing", "random message": 0, "message_id": mess["message_id"], "username": button_clicker_username, } break except: db.child("all_message").child( str(button_chat_id)).child( str(the_message_in_firebase)).remove() elif query.data == "DELETE THIS": message_id = the_bot[button_chat_id][button_clicker_id][ "random message"] if message_id != 0: db.child("all_message").child(str(button_chat_id)).child( str(message_id)).remove() reply_markup = InlineKeyboardMarkup(keyboard4) context.bot.delete_message( chat_id=button_chat_id, message_id=the_bot[button_chat_id][button_clicker_id] ["message_id"], ) context.bot.send_message( chat_id=button_chat_id, text="This message has been deleted", reply_to_message_id=message_id, ) mess = context.bot.send_message( chat_id=button_chat_id, text="Please choose what you want :", reply_markup=reply_markup, ) the_bot[button_chat_id][button_clicker_id] = { "state": "RANDOM", "random message": 0, "message_id": mess["message_id"], "username": button_clicker_username, } else: context.bot.delete_message(chat_id=button_chat_id, message_id=button_message_id) else: the_bot[button_chat_id][button_clicker_id] = { "state": "NOTHING", "random message": 0, "username": button_clicker_username, } else: try: context.bot.delete_message(chat_id=button_chat_id, message_id=button_message_id) except: pass if (bot_message["text"] != f"{button_clicker_username} you don't have access to the bot if you want to use it click /start" ): bot_message = context.bot.send_message( chat_id=button_chat_id, text= f"{button_clicker_username} you don't have access to the bot if you want to use it click /start", ) except: error = traceback.format_exc() error_handle(context, button_chat_id, error) the_bot.pop(button_chat_id)
firebase = pyrebase.initialize_app(TheConfig.config) db = firebase.database() # --------- for enable the telegram bot --------- # updater = Updater(TheConfig.token, use_context=True) bot = Bot(TheConfig.token) # the_bot = {} bot_message = {"text": " "} keyboard4 = [ [InlineKeyboardButton("Add New Massage", callback_data="ADD")], [InlineKeyboardButton("Delete a Message", callback_data="DELETE")], [InlineKeyboardButton("Send a Random Message", callback_data="RANDOM")], [InlineKeyboardButton("Stop The Bot", callback_data="STOP")], ] keyboard2 = [ [InlineKeyboardButton("Add New Massage", callback_data="ADD")], [InlineKeyboardButton("Stop The Bot", callback_data="STOP")], ] def error_handle(context, chat_id, error): global bot_message
def user(update: Update, context: CallbackContext): message = update.effective_message args = message.text.strip().split(" ", 1) try: search_query = args[1] except: if message.reply_to_message: search_query = message.reply_to_message.text else: update.effective_message.reply_text("Format : /user <username>") return jikan = jikanpy.jikan.Jikan() try: user = jikan.user(search_query) except jikanpy.APIException: update.effective_message.reply_text("Username not found.") return progress_message = update.effective_message.reply_text("Searching.... ") date_format = "%Y-%m-%d" if user['image_url'] is None: img = "https://cdn.myanimelist.net/images/questionmark_50.gif" else: img = user['image_url'] try: user_birthday = datetime.datetime.fromisoformat(user['birthday']) user_birthday_formatted = user_birthday.strftime(date_format) except: user_birthday_formatted = "Unknown" user_joined_date = datetime.datetime.fromisoformat(user['joined']) user_joined_date_formatted = user_joined_date.strftime(date_format) for entity in user: if user[entity] is None: user[entity] = "Unknown" about = user['about'].split(" ", 60) try: about.pop(60) except IndexError: pass about_string = ' '.join(about) about_string = about_string.replace("<br>", "").strip().replace("\r\n", "\n") caption = "" caption += textwrap.dedent(f""" *Username*: [{user['username']}]({user['url']}) *Gender*: `{user['gender']}` *Birthday*: `{user_birthday_formatted}` *Joined*: `{user_joined_date_formatted}` *Days wasted watching anime*: `{user['anime_stats']['days_watched']}` *Days wasted reading manga*: `{user['manga_stats']['days_read']}` """) caption += f"*About*: {about_string}" buttons = [[InlineKeyboardButton(info_btn, url=user['url'])], [ InlineKeyboardButton( close_btn, callback_data=f"anime_close, {message.from_user.id}") ]] update.effective_message.reply_photo( photo=img, caption=caption, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=False) progress_message.delete()
def options_list_buttons(self, list_): return [InlineKeyboardButton( value, callback_data=key ) for key, value in enumerate(list_)]
class TestInlineQueryResultVenue(object): id_ = 'id' type_ = 'venue' latitude = 'latitude' longitude = 'longitude' title = 'title' address = 'address' foursquare_id = 'foursquare id' foursquare_type = 'foursquare type' thumb_url = 'thumb url' thumb_width = 10 thumb_height = 15 input_message_content = InputTextMessageContent('input_message_content') reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]]) def test_expected_values(self, inline_query_result_venue): assert inline_query_result_venue.id == self.id_ assert inline_query_result_venue.type == self.type_ assert inline_query_result_venue.latitude == self.latitude assert inline_query_result_venue.longitude == self.longitude assert inline_query_result_venue.title == self.title assert inline_query_result_venue.address == self.address assert inline_query_result_venue.foursquare_id == self.foursquare_id assert inline_query_result_venue.foursquare_type == self.foursquare_type assert inline_query_result_venue.thumb_url == self.thumb_url assert inline_query_result_venue.thumb_width == self.thumb_width assert inline_query_result_venue.thumb_height == self.thumb_height assert (inline_query_result_venue.input_message_content.to_dict() == self.input_message_content.to_dict()) assert inline_query_result_venue.reply_markup.to_dict() == self.reply_markup.to_dict() def test_to_dict(self, inline_query_result_venue): inline_query_result_venue_dict = inline_query_result_venue.to_dict() assert isinstance(inline_query_result_venue_dict, dict) assert inline_query_result_venue_dict['id'] == inline_query_result_venue.id assert inline_query_result_venue_dict['type'] == inline_query_result_venue.type assert inline_query_result_venue_dict['latitude'] == inline_query_result_venue.latitude assert inline_query_result_venue_dict['longitude'] == inline_query_result_venue.longitude assert inline_query_result_venue_dict['title'] == inline_query_result_venue.title assert inline_query_result_venue_dict['address'] == inline_query_result_venue.address assert (inline_query_result_venue_dict['foursquare_id'] == inline_query_result_venue.foursquare_id) assert (inline_query_result_venue_dict['foursquare_type'] == inline_query_result_venue.foursquare_type) assert inline_query_result_venue_dict['thumb_url'] == inline_query_result_venue.thumb_url assert (inline_query_result_venue_dict['thumb_width'] == inline_query_result_venue.thumb_width) assert (inline_query_result_venue_dict['thumb_height'] == inline_query_result_venue.thumb_height) assert (inline_query_result_venue_dict['input_message_content'] == inline_query_result_venue.input_message_content.to_dict()) assert (inline_query_result_venue_dict['reply_markup'] == inline_query_result_venue.reply_markup.to_dict()) def test_equality(self): a = InlineQueryResultVenue(self.id_, self.longitude, self.latitude, self.title, self.address) b = InlineQueryResultVenue(self.id_, self.longitude, self.latitude, self.title, self.address) c = InlineQueryResultVenue(self.id_, '', self.latitude, self.title, self.address) d = InlineQueryResultVenue('', self.longitude, self.latitude, self.title, self.address) e = InlineQueryResultVoice(self.id_, '', '') assert a == b assert hash(a) == hash(b) assert a is not b assert a == c assert hash(a) == hash(c) assert a != d assert hash(a) != hash(d) assert a != e assert hash(a) != hash(e)
def settings_button(bot: Bot, update: Update): query = update.callback_query user = update.effective_user mod_match = re.match(r"stngs_module\((.+?),(.+?)\)", query.data) prev_match = re.match(r"stngs_prev\((.+?),(.+?)\)", query.data) next_match = re.match(r"stngs_next\((.+?),(.+?)\)", query.data) back_match = re.match(r"stngs_back\((.+?)\)", query.data) try: if mod_match: chat_id = mod_match.group(1) module = mod_match.group(2) chat = bot.get_chat(chat_id) text = "*{}*, *{}* modülü için aşağıdaki ayarlara sahiptir:\n\n".format(escape_markdown(chat.title), CHAT_SETTINGS[ module].__mod_name__) + \ CHAT_SETTINGS[module].__chat_settings__(chat_id, user.id) query.message.reply_text( text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text="Geri", callback_data="stngs_back({})".format(chat_id)) ]])) elif prev_match: chat_id = prev_match.group(1) curr_page = int(prev_match.group(2)) chat = bot.get_chat(chat_id) query.message.reply_text( "Vay arkadaş! {} için epeyce ayar var - Devam et ve " "ilgilendiğin şeyi seç.".format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(curr_page - 1, CHAT_SETTINGS, "stngs", chat=chat_id))) elif next_match: chat_id = next_match.group(1) next_page = int(next_match.group(2)) chat = bot.get_chat(chat_id) query.message.reply_text( "Vay arkadaş! {} için epeyce ayar var - Devam et ve " "ilgilendiğin şeyi seç.".format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(next_page + 1, CHAT_SETTINGS, "stngs", chat=chat_id))) elif back_match: chat_id = back_match.group(1) chat = bot.get_chat(chat_id) query.message.reply_text( text="Vay arkadaş! {} için epeyce ayar var - Devam et ve " "ilgilendiğin şeyi seç.".format(escape_markdown(chat.title)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules(0, CHAT_SETTINGS, "stngs", chat=chat_id))) # ensure no spinny white circle bot.answer_callback_query(query.id) query.message.delete() except BadRequest as excp: if excp.message == "The message has not been changed": pass elif excp.message == "Query_id_invalid": pass elif excp.message == "Stop right there! This message cannot be deleted": pass else: LOGGER.exception("Exception in settings buttons. %s", str(query.data))
def report(update: Update, context: CallbackContext) -> str: bot = context.bot args = context.args message = update.effective_message chat = update.effective_chat user = update.effective_user if chat and message.reply_to_message and sql.chat_should_report(chat.id): reported_user = message.reply_to_message.from_user chat_name = chat.title or chat.first or chat.username admin_list = chat.get_administrators() message = update.effective_message if not args: message.reply_text("Add a reason for reporting first.") return "" if user.id == reported_user.id: message.reply_text("Uh yeah, Sure sure...maso much?") return "" if user.id == bot.id: message.reply_text("Nice try.") return "" if reported_user.id in REPORT_IMMUNE_USERS: message.reply_text("Uh? You reporting a super user?") return "" if chat.username and chat.type == Chat.SUPERGROUP: reported = f"{mention_html(user.id, user.first_name)} reported {mention_html(reported_user.id, reported_user.first_name)} to the admins!" msg = ( f"<b>⚠️ Report: </b>{html.escape(chat.title)}\n" f"<b> • Report by:</b> {mention_html(user.id, user.first_name)}(<code>{user.id}</code>)\n" f"<b> • Reported user:</b> {mention_html(reported_user.id, reported_user.first_name)} (<code>{reported_user.id}</code>)\n" ) link = f'<b> • Reported message:</b> <a href="https://t.me/{chat.username}/{message.reply_to_message.message_id}">click here</a>' should_forward = False keyboard = [ [ InlineKeyboardButton( u"➡ Message", url= f"https://t.me/{chat.username}/{message.reply_to_message.message_id}" ) ], [ InlineKeyboardButton( u"⚠ Kick", callback_data= f"report_{chat.id}=kick={reported_user.id}={reported_user.first_name}" ), InlineKeyboardButton( u"⛔️ Ban", callback_data= f"report_{chat.id}=banned={reported_user.id}={reported_user.first_name}" ) ], [ InlineKeyboardButton( u"❎ Delete Message", callback_data= f"report_{chat.id}=delete={reported_user.id}={message.reply_to_message.message_id}" ) ] ] reply_markup = InlineKeyboardMarkup(keyboard) else: reported = f"{mention_html(user.id, user.first_name)} reported " \ f"{mention_html(reported_user.id, reported_user.first_name)} to the admins!" msg = f'{mention_html(user.id, user.first_name)} is calling for admins in "{html.escape(chat_name)}"!' link = "" should_forward = True for admin in admin_list: if admin.user.is_bot: # can't message bots continue if sql.user_should_report(admin.user.id): try: if not chat.type == Chat.SUPERGROUP: bot.send_message(admin.user.id, msg + link, parse_mode=ParseMode.HTML) if should_forward: message.reply_to_message.forward(admin.user.id) if len( message.text.split() ) > 1: # If user is giving a reason, send his message too message.forward(admin.user.id) if not chat.username: bot.send_message(admin.user.id, msg + link, parse_mode=ParseMode.HTML) if should_forward: message.reply_to_message.forward(admin.user.id) if len( message.text.split() ) > 1: # If user is giving a reason, send his message too message.forward(admin.user.id) if chat.username and chat.type == Chat.SUPERGROUP: bot.send_message(admin.user.id, msg + link, parse_mode=ParseMode.HTML, reply_markup=reply_markup) if should_forward: message.reply_to_message.forward(admin.user.id) if len( message.text.split() ) > 1: # If user is giving a reason, send his message too message.forward(admin.user.id) except Unauthorized: pass except BadRequest as excp: # TODO: cleanup exceptions LOGGER.exception("Exception while reporting user") message.reply_to_message.reply_text( f"{mention_html(user.id, user.first_name)} reported the message to the admins.", parse_mode=ParseMode.HTML) return msg return ""
def warn(user: User, chat: Chat, reason: str, message: Message, warner: User = None) -> str: if is_user_admin(chat, user.id): message.reply_text("Damn admins, can't even be warned!") return "" if warner: warner_tag = mention_html(warner.id, warner.first_name) else: warner_tag = "Automated warn filter." limit, soft_warn = sql.get_warn_setting(chat.id) num_warns, reasons = sql.warn_user(user.id, chat.id, reason) if num_warns >= limit: sql.reset_warns(user.id, chat.id) if soft_warn: # kick chat.unban_member(user.id) reply = "{} warnings, {} has been kicked!".format( limit, mention_html(user.id, user.first_name)) else: # ban chat.kick_member(user.id) reply = "{} warnings, {} has been banned!".format( limit, mention_html(user.id, user.first_name)) for warn_reason in reasons: reply += "\n - {}".format(html.escape(warn_reason)) message.bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker keyboard = [] log_reason = "<b>{}:</b>" \ "\n#WARN_BAN" \ "\n<b>Admin:</b> {}" \ "\n<b>User:</b> {}" \ "\n<b>Reason:</b> {}".format(html.escape(chat.title), warner_tag, mention_html(user.id, user.first_name), reason) else: keyboard = InlineKeyboardMarkup([[ InlineKeyboardButton("Remove warn", callback_data="rm_warn({})".format(user.id)) ]]) reply = "{} has {}/{} warnings... watch out!".format( mention_html(user.id, user.first_name), num_warns, limit) if reason: reply += "\nReason for last warn:\n{}".format(html.escape(reason)) log_reason = "<b>{}:</b>" \ "\n#WARN" \ "\n<b>Admin:</b> {}" \ "\n<b>User:</b> {}" \ "\n<b>Reason:</b> {}".format(html.escape(chat.title), warner_tag, mention_html(user.id, user.first_name), reason) try: message.reply_text(reply, reply_markup=keyboard, parse_mode=ParseMode.HTML) except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text(reply, reply_markup=keyboard, parse_mode=ParseMode.HTML, quote=False) else: raise return log_reason
def extract_image(update: Update, context: CallbackContext): ''' This function is called when the user sends a photo. ''' chat_id = update.effective_chat.id file_id = update.message.photo[-1].file_id newFile = context.bot.get_file(file_id) file_path = newFile.file_path keyboard = [[ InlineKeyboardButton("English ", callback_data='eng'), InlineKeyboardButton("Russian", callback_data='rus'), InlineKeyboardButton("Czech", callback_data='cze') ], [ InlineKeyboardButton("Chinese simplified", callback_data='chs'), InlineKeyboardButton("Chinese Traditional", callback_data='cht') ], [InlineKeyboardButton("Japanese", callback_data='jpn')], [ InlineKeyboardButton("Arabic", callback_data='ara'), InlineKeyboardButton("Afrikans", callback_data='AFR'), InlineKeyboardButton("German", callback_data='gre') ], [ InlineKeyboardButton("Italian", callback_data='ita'), InlineKeyboardButton("Indonesian", callback_data='eng'), InlineKeyboardButton("French", callback_data='fre') ], [ InlineKeyboardButton("Spanish", callback_data='spa'), InlineKeyboardButton("Portuguese", callback_data='por'), InlineKeyboardButton("Korean", callback_data='kor') ]] reply_markup = InlineKeyboardMarkup(keyboard) m = update.message.reply_text('Select Language : ', reply_markup=reply_markup, quote=True) insert_file_path(chat_id, m.message_id, file_path)
def main_handle(sticker_number, chat_id, main_message, all_stickers, title): try: a = bot.getStickerSet(name="line" + str(sticker_number) + "_by_RekcitsEnilbot") a_len = len(a.stickers) status = 1 except: a = 0 a_len = 0 status = -1 global continue_handle continue_handle = True threading.Timer( 20, con_req, [sticker_number, chat_id, main_message, all_stickers, title]).start() head_sticker = 0 temp_message = title + "\n發現" + str( len(all_stickers)) + "張貼圖\n\nFound " + str( len(all_stickers)) + " stickers\n" for i in range(a_len, len(all_stickers)): if continue_handle == False: return z = requests.get(all_stickers[i]).content open('temp.png', 'wb').write(z) img = Image.open('temp.png').convert('RGBA') arr = np.array(img) mag = 512 / max(len(arr[0]), len(arr)) new_arr = handle_image(mag, arr) Image.fromarray(new_arr, 'RGBA').save("output" + str(i) + ".png") sticker = bot.uploadStickerFile(user_id=chat_id, png_sticker=open( "output" + str(i) + ".png", 'rb')).file_id rnd_emoji = random_emoji() if i == 0 and status == -1: head_sticker = sticker bot.createNewStickerSet(user_id=chat_id, name="line" + str(sticker_number) + "_by_RekcitsEnilbot", title=title + " @RekcitsEnilbot", png_sticker=sticker, emojis=rnd_emoji) else: if len( bot.getStickerSet(name="line" + str(sticker_number) + "_by_RekcitsEnilbot").stickers) != i: bot.editMessageText( chat_id=chat_id, message_id=main_message, text= "出了點問題,具體來說是同時有兩個在上傳貼圖\n\nError:Multi thread is not available." ) return bot.addStickerToSet(user_id=chat_id, name="line" + str(sticker_number) + "_by_RekcitsEnilbot", png_sticker=sticker, emojis=rnd_emoji) '''bot.sendDocument(chat_id = update.message.chat.id, document = open("output"+str(i)+".png", 'rb'), caption = "")''' temp_message2 = temp_message for j in range(i + 1): temp_message2 += "■" for j in range(len(all_stickers) - i - 1): temp_message2 += "_" temp_message2 += str(i + 1) + "/" + str(len(all_stickers)) bot.editMessageText(chat_id=chat_id, message_id=main_message, text=temp_message2) continue_handle = False bot.sendMessage(chat_id=chat_id, text="噠啦~☆\n\nFinished!" + "\n\nLine sticker number:" + str(sticker_number) + "\nhttps://t.me/addstickers/line" + str(sticker_number) + "_by_RekcitsEnilbot") if head_sticker == 0: head_sticker = a.stickers[0].file_id bot.sendSticker( chat_id=chat_id, sticker=head_sticker, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton(text=title, url="https://t.me/addstickers/line" + str(sticker_number) + "_by_RekcitsEnilbot") ]])) return
aeval = Interpreter() #Using this instead of eval from telegram import InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import (Updater, CommandHandler, CallbackQueryHandler) import logging # Enable logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) In_reply_keyboard = [[ InlineKeyboardButton("7", callback_data='7'), InlineKeyboardButton("8", callback_data='8'), InlineKeyboardButton("9", callback_data='9'), InlineKeyboardButton("+", callback_data='+') ], [ InlineKeyboardButton("4", callback_data='4'), InlineKeyboardButton("5", callback_data='5'), InlineKeyboardButton("6", callback_data='6'), InlineKeyboardButton("-", callback_data='-'), ], [ InlineKeyboardButton("1", callback_data='1'), InlineKeyboardButton("2", callback_data='2'), InlineKeyboardButton("3", callback_data='3'), InlineKeyboardButton("*", callback_data='*')
def settings_button(bot: Bot, update: Update): query = update.callback_query user = update.effective_user mod_match = re.match(r"stngs_module\((.+?),(.+?)\)", query.data) prev_match = re.match(r"stngs_prev\((.+?),(.+?)\)", query.data) next_match = re.match(r"stngs_next\((.+?),(.+?)\)", query.data) back_match = re.match(r"stngs_back\((.+?)\)", query.data) try: if mod_match: chat_id = mod_match.group(1) module = mod_match.group(2) chat = bot.get_chat(chat_id) text = "*{}* memiliki pengaturan berikut untuk modul *{}*:\n\n".format( escape_markdown(chat.title), CHAT_SETTINGS[module].__mod_name__ ) + CHAT_SETTINGS[module].__chat_settings__(chat_id, user.id) query.message.reply_text( text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( [ [ InlineKeyboardButton( text="Kembali", callback_data="stngs_back({})".format(chat_id), ) ] ] ), ) elif prev_match: chat_id = prev_match.group(1) curr_page = int(prev_match.group(2)) chat = bot.get_chat(chat_id) query.message.reply_text( "Halo yang disana! Ada beberapa setelan untuk {} - lanjutkan dan pilih apa " "yang Anda tertarik.".format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules( curr_page - 1, CHAT_SETTINGS, "stngs", chat=chat_id ) ), ) elif next_match: chat_id = next_match.group(1) next_page = int(next_match.group(2)) chat = bot.get_chat(chat_id) query.message.reply_text( "Halo yang disana! Ada beberapa setelan untuk {} - lanjutkan dan pilih apa " "yang Anda tertarik.".format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules( next_page + 1, CHAT_SETTINGS, "stngs", chat=chat_id ) ), ) elif back_match: chat_id = back_match.group(1) chat = bot.get_chat(chat_id) query.message.reply_text( text="Halo yang disana! Ada beberapa setelan untuk {} - lanjutkan dan pilih apa " "yang Anda tertarik.".format(escape_markdown(chat.title)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules(0, CHAT_SETTINGS, "stngs", chat=chat_id) ), ) # ensure no spinny white circle bot.answer_callback_query(query.id) query.message.delete() except BadRequest as excp: if excp.message == "Pesan tidak diubah": pass elif excp.message == "Query_id_invalid": pass elif excp.message == "Pesan tidak dapat dihapus": pass else: LOGGER.exception("Exception in settings buttons. %s", str(query.data))
def connect_chat(update, context): chat = update.effective_chat user = update.effective_user args = context.args if update.effective_chat.type == "private": if args and len(args) >= 1: try: connect_chat = int(args[0]) getstatusadmin = context.bot.get_chat_member( connect_chat, update.effective_message.from_user.id) except ValueError: try: connect_chat = str(args[0]) get_chat = context.bot.getChat(connect_chat) connect_chat = get_chat.id getstatusadmin = context.bot.get_chat_member( connect_chat, update.effective_message.from_user.id) except BadRequest: send_message(update.effective_message, "Invalid Chat ID!") return except BadRequest: send_message(update.effective_message, "Invalid Chat ID!") return isadmin = getstatusadmin.status in ("administrator", "creator") ismember = getstatusadmin.status in ("member") isallow = sql.allow_connect_to_chat(connect_chat) if (isadmin) or (isallow and ismember) or (user.id in DRAGONS): connection_status = sql.connect( update.effective_message.from_user.id, connect_chat) if connection_status: conn_chat = dispatcher.bot.getChat( connected(context.bot, update, chat, user.id, need_admin=False)) chat_name = conn_chat.title send_message( update.effective_message, "Successfully connected to *{}*. \nUse /helpconnect to check available commands." .format(chat_name), parse_mode=ParseMode.MARKDOWN, ) sql.add_history_conn(user.id, str(conn_chat.id), chat_name) else: send_message(update.effective_message, "Connection failed!") else: send_message(update.effective_message, "Connection to this chat is not allowed!") else: gethistory = sql.get_history_conn(user.id) if gethistory: buttons = [ InlineKeyboardButton(text="❎ Close button", callback_data="connect_close"), InlineKeyboardButton(text="🧹 Clear history", callback_data="connect_clear"), ] else: buttons = [] conn = connected(context.bot, update, chat, user.id, need_admin=False) if conn: connectedchat = dispatcher.bot.getChat(conn) text = "You are currently connected to *{}* (`{}`)".format( connectedchat.title, conn) buttons.append( InlineKeyboardButton(text="🔌 Disconnect", callback_data="connect_disconnect")) else: text = "Write the chat ID or tag to connect!" if gethistory: text += "\n\n*Connection history:*\n" text += "╒═══「 *Info* 」\n" text += "│ Sorted: `Newest`\n" text += "│\n" buttons = [buttons] for x in sorted(gethistory.keys(), reverse=True): htime = time.strftime("%d/%m/%Y", time.localtime(x)) text += "╞═「 *{}* 」\n│ `{}`\n│ `{}`\n".format( gethistory[x]["chat_name"], gethistory[x]["chat_id"], htime) text += "│\n" buttons.append([ InlineKeyboardButton( text=gethistory[x]["chat_name"], callback_data="connect({})".format( gethistory[x]["chat_id"]), ) ]) text += "╘══「 Total {} Chats 」".format( str(len(gethistory)) + " (max)" if len(gethistory) == 5 else str(len(gethistory))) conn_hist = InlineKeyboardMarkup(buttons) elif buttons: conn_hist = InlineKeyboardMarkup([buttons]) else: conn_hist = None send_message( update.effective_message, text, parse_mode="markdown", reply_markup=conn_hist, ) else: getstatusadmin = context.bot.get_chat_member( chat.id, update.effective_message.from_user.id) isadmin = getstatusadmin.status in ("administrator", "creator") ismember = getstatusadmin.status in ("member") isallow = sql.allow_connect_to_chat(chat.id) if (isadmin) or (isallow and ismember) or (user.id in DRAGONS): connection_status = sql.connect( update.effective_message.from_user.id, chat.id) if connection_status: chat_name = dispatcher.bot.getChat(chat.id).title send_message( update.effective_message, "Successfully connected to *{}*.".format(chat_name), parse_mode=ParseMode.MARKDOWN, ) try: sql.add_history_conn(user.id, str(chat.id), chat_name) context.bot.send_message( update.effective_message.from_user.id, "You are connected to *{}*. \nUse `/helpconnect` to check available commands." .format(chat_name), parse_mode="markdown", ) except BadRequest: pass except Unauthorized: pass else: send_message(update.effective_message, "Connection failed!") else: send_message(update.effective_message, "Connection to this chat is not allowed!")
def new_member(update: Update, context: CallbackContext): bot, job_queue = context.bot, context.job_queue chat = update.effective_chat user = update.effective_user msg = update.effective_message should_welc, cust_welcome, cust_content, welc_type = sql.get_welc_pref( chat.id) welc_mutes = sql.welcome_mutes(chat.id) human_checks = sql.get_human_checks(user.id, chat.id) new_members = update.effective_message.new_chat_members for new_mem in new_members: welcome_log = None res = None sent = None should_mute = True welcome_bool = True media_wel = False if sw is not None: sw_ban = sw.get_ban(new_mem.id) if sw_ban: return if should_welc: reply = update.message.message_id cleanserv = sql.clean_service(chat.id) # Clean service welcome if cleanserv: try: dispatcher.bot.delete_message(chat.id, update.message.message_id) except BadRequest: pass reply = False # Give the owner a special welcome if new_mem.id == OWNER_ID: update.effective_message.reply_text( "Oh, Genos? Hadi bunu harekete geçirelim.", reply_to_message_id=reply) welcome_log = (f"{html.escape(chat.title)}\n" f"#USER_BİRLEŞTİRİLDİ\n" f"Bot Sahibi sohbete yeni katıldı") continue # Welcome Devs elif new_mem.id in DEV_USERS: update.effective_message.reply_text( "Vay be! Kahramanlar Derneği'nin bir üyesi az önce katıldı!", reply_to_message_id=reply, ) continue # Welcome Sudos elif new_mem.id in DRAGONS: update.effective_message.reply_text( "Huh! Bir Dragon felaketi az önce katıldı! Dikkatli Kalın!", reply_to_message_id=reply, ) continue # Welcome Support elif new_mem.id in DEMONS: update.effective_message.reply_text( "Huh! Demon felaket seviyesine sahip biri az önce katıldı!", reply_to_message_id=reply, ) continue # Welcome Whitelisted elif new_mem.id in TIGERS: update.effective_message.reply_text( "Oof! Bir Kaplan felaketi yeni katıldı!", reply_to_message_id=reply) continue # Welcome Tigers elif new_mem.id in WOLVES: update.effective_message.reply_text( "Oof! Bir Kurt felaketi yeni katıldı!", reply_to_message_id=reply) continue # Welcome yourself elif new_mem.id == bot.id: creator = None for x in bot.bot.get_chat_administrators( update.effective_chat.id): if x.status == 'creator': creator = x.user break if creator: bot.send_message( JOIN_LOGGER, "#NEW_GROUP\n<b>Group name:</b> {}\n<b>ID:</b> <code>{}</code>\n<b>Creator:</b> <code>{}</code>" .format(html.escape(chat.title), chat.id, html.escape(creator)), parse_mode=ParseMode.HTML) else: bot.send_message( JOIN_LOGGER, "#NEW_GROUP\n<b>Group name:</b> {}\n<b>ID:</b> <code>{}</code>" .format(html.escape(chat.title), chat.id), parse_mode=ParseMode.HTML) update.effective_message.reply_text("Watashi ga kita!", reply_to_message_id=reply) continue else: buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard(buttons) if welc_type not in (sql.Types.TEXT, sql.Types.BUTTON_TEXT): media_wel = True first_name = ( new_mem.first_name or "PersonWithNoName" ) # edge case of empty name - occurs for some bugs. if cust_welcome: if cust_welcome == sql.DEFAULT_WELCOME: cust_welcome = random.choice( sql.DEFAULT_WELCOME_MESSAGES).format( first=escape_markdown(first_name)) if new_mem.last_name: fullname = escape_markdown( f"{first_name} {new_mem.last_name}") else: fullname = escape_markdown(first_name) count = chat.get_members_count() mention = mention_markdown(new_mem.id, escape_markdown(first_name)) if new_mem.username: username = "******" + escape_markdown(new_mem.username) else: username = mention valid_format = escape_invalid_curly_brackets( cust_welcome, VALID_WELCOME_FORMATTERS) res = valid_format.format( first=escape_markdown(first_name), last=escape_markdown(new_mem.last_name or first_name), fullname=escape_markdown(fullname), username=username, mention=mention, count=count, chatname=escape_markdown(chat.title), id=new_mem.id, ) else: res = random.choice(sql.DEFAULT_WELCOME_MESSAGES).format( first=escape_markdown(first_name)) keyb = [] backup_message = random.choice( sql.DEFAULT_WELCOME_MESSAGES).format( first=escape_markdown(first_name)) keyboard = InlineKeyboardMarkup(keyb) else: welcome_bool = False res = None keyboard = None backup_message = None reply = None # User exceptions from welcomemutes if (is_user_ban_protected(chat, new_mem.id, chat.get_member( new_mem.id)) or human_checks): should_mute = False # Join welcome: soft mute if new_mem.is_bot: should_mute = False if user.id == new_mem.id: if should_mute: if welc_mutes == "soft": bot.restrict_chat_member( chat.id, new_mem.id, permissions=ChatPermissions( can_send_messages=True, can_send_media_messages=False, can_send_other_messages=False, can_invite_users=False, can_pin_messages=False, can_send_polls=False, can_change_info=False, can_add_web_page_previews=False, ), until_date=(int(time.time() + 24 * 60 * 60)), ) if welc_mutes == "strong": welcome_bool = False if not media_wel: VERIFIED_USER_WAITLIST.update({ new_mem.id: { "should_welc": should_welc, "media_wel": False, "status": False, "update": update, "res": res, "keyboard": keyboard, "backup_message": backup_message, } }) else: VERIFIED_USER_WAITLIST.update({ new_mem.id: { "should_welc": should_welc, "chat_id": chat.id, "status": False, "media_wel": True, "cust_content": cust_content, "welc_type": welc_type, "res": res, "keyboard": keyboard, } }) new_join_mem = f'<a href="tg://user?id={user.id}">{html.escape(new_mem.first_name)}</a>' message = msg.reply_text( f"{new_join_mem}, insan olduğunuzu kanıtlamak için aşağıdaki düğmeyi tıklayın.\n120 saniyeniz var.", reply_markup=InlineKeyboardMarkup([{ InlineKeyboardButton( text="Evet, ben insanım.", callback_data=f"user_join_({new_mem.id})", ) }]), parse_mode=ParseMode.HTML, reply_to_message_id=reply, ) bot.restrict_chat_member( chat.id, new_mem.id, permissions=ChatPermissions( can_send_messages=False, can_invite_users=False, can_pin_messages=False, can_send_polls=False, can_change_info=False, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False, ), ) job_queue.run_once( partial(check_not_bot, new_mem, chat.id, message.message_id), 120, name="welcomemute", ) if welcome_bool: if media_wel: sent = ENUM_FUNC_MAP[welc_type]( chat.id, cust_content, caption=res, reply_markup=keyboard, reply_to_message_id=reply, parse_mode="markdown", ) else: sent = send(update, res, keyboard, backup_message) prev_welc = sql.get_clean_pref(chat.id) if prev_welc: try: bot.delete_message(chat.id, prev_welc) except BadRequest: pass if sent: sql.set_clean_welcome(chat.id, sent.message_id) if welcome_log: return welcome_log return (f"{html.escape(chat.title)}\n" f"#USER_JOINED\n" f"<b>User</b>: {mention_html(user.id, user.first_name)}\n" f"<b>ID</b>: <code>{user.id}</code>") return ""
def warn(user: User, chat: Chat, reason: str, message: Message, warner: User = None, conn=False) -> str: if is_user_admin(chat, user.id): return "" if warner: warner_tag = mention_html(warner.id, warner.first_name) else: warner_tag = tl(chat.id, "Filter peringatan otomatis.") limit, soft_warn, warn_mode = sql.get_warn_setting(chat.id) num_warns, reasons = sql.warn_user(user.id, chat.id, reason) if num_warns >= limit: sql.reset_warns(user.id, chat.id) if not soft_warn: if not warn_mode: chat.unban_member(user.id) reply = tl(chat.id, "{} peringatan, {} telah ditendang!").format( limit, mention_html(user.id, user.first_name)) elif warn_mode == 1: chat.unban_member(user.id) reply = tl(chat.id, "{} peringatan, {} telah ditendang!").format( limit, mention_html(user.id, user.first_name)) elif warn_mode == 2: chat.kick_member(user.id) reply = tl(chat.id, "{} peringatan, {} telah diblokir!").format( limit, mention_html(user.id, user.first_name)) elif warn_mode == 3: message.bot.restrict_chat_member(chat.id, user.id, can_send_messages=False) reply = tl(chat.id, "{} peringatan, {} telah dibisukan!").format( limit, mention_html(user.id, user.first_name)) else: chat.kick_member(user.id) reply = tl(chat.id, "{} peringatan, {} telah diblokir!").format( limit, mention_html(user.id, user.first_name)) for warn_reason in reasons: reply += "\n - {}".format(html.escape(warn_reason)) message.bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker keyboard = None log_reason = "<b>{}:</b>" \ "\n#WARN_BAN" \ "\n<b>Admin:</b> {}" \ "\n<b>User:</b> {} (<code>{}</code>)" \ "\n<b>Reason:</b> {}"\ "\n<b>Counts:</b> <code>{}/{}</code>".format(html.escape(chat.title), warner_tag, mention_html(user.id, user.first_name), user.id, reason, num_warns, limit) else: keyboard = InlineKeyboardMarkup([[ InlineKeyboardButton(tl(chat.id, "Hapus peringatan"), callback_data="rm_warn({})".format(user.id)), InlineKeyboardButton(tl(chat.id, "Peraturan"), url="t.me/{}?start={}".format( dispatcher.bot.username, chat.id)) ]]) if num_warns + 1 == limit: if not warn_mode: action_mode = tl(chat.id, "tendang") elif warn_mode == 1: action_mode = tl(chat.id, "tendang") elif warn_mode == 2: action_mode = tl(chat.id, "blokir") elif warn_mode == 3: action_mode = tl(chat.id, "bisukan") reply = tl( chat.id, "{} punya {}/{} peringatan... Jika anda di peringati lagi maka kamu akan di {}!" ).format(mention_html(user.id, user.first_name), num_warns, limit, action_mode) else: reply = tl(chat.id, "{} punya {}/{} peringatan... Hati-hati!").format( mention_html(user.id, user.first_name), num_warns, limit) if reason: reply += tl(chat.id, "\nAlasan pada peringatan terakhir:\n{}").format( html.escape(reason)) log_reason = "<b>{}:</b>" \ "\n#WARN" \ "\n<b>Admin:</b> {}" \ "\n<b>User:</b> {} (<code>{}</code>)" \ "\n<b>Reason:</b> {}"\ "\n<b>Counts:</b> <code>{}/{}</code>".format(html.escape(chat.title), warner_tag, mention_html(user.id, user.first_name), user.id, reason, num_warns, limit) try: if conn: send_message_raw(chat.id, reply, reply_markup=keyboard, parse_mode=ParseMode.HTML) else: send_message_raw(chat.id, reply, reply_to_message_id=message.message_id, reply_markup=keyboard, parse_mode=ParseMode.HTML) # send_message(update.effective_message, reply, reply_markup=keyboard, parse_mode=ParseMode.HTML) except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply if conn: message.bot.sendMessage(chat.id, reply, reply_markup=keyboard, parse_mode=ParseMode.HTML) else: try: message.bot.sendMessage( chat.id, reply, reply_to_message_id=message.message_id, reply_markup=keyboard, parse_mode=ParseMode.HTML, quote=False) except BadRequest: message.bot.sendMessage(chat.id, reply, reply_markup=keyboard, parse_mode=ParseMode.HTML, quote=False) # send_message(update.effective_message, reply, reply_markup=keyboard, parse_mode=ParseMode.HTML, quote=False) else: raise return log_reason
def anime(update: Update, context: CallbackContext): message = update.effective_message search = message.text.split(' ', 1) if len(search) == 1: update.effective_message.reply_text('Format : /anime < anime name >') return else: search = search[1] variables = {'search': search} json = requests.post(url, json={ 'query': anime_query, 'variables': variables }).json() if 'errors' in json.keys(): update.effective_message.reply_text('Anime not found') return if json: json = json['data']['Media'] msg = f"*{json['title']['romaji']}*(`{json['title']['native']}`)\n*Type*: {json['format']}\n*Status*: {json['status']}\n*Episodes*: {json.get('episodes', 'N/A')}\n*Duration*: {json.get('duration', 'N/A')} Per Ep.\n*Score*: {json['averageScore']}\n*Genres*: `" for x in json['genres']: msg += f"{x}, " msg = msg[:-2] + '`\n' msg += "*Studios*: `" for x in json['studios']['nodes']: msg += f"{x['name']}, " msg = msg[:-2] + '`\n' info = json.get('siteUrl') trailer = json.get('trailer', None) anime_id = json['id'] if trailer: trailer_id = trailer.get('id', None) site = trailer.get('site', None) if site == "youtube": trailer = 'https://youtu.be/' + trailer_id description = json.get('description', 'N/A').replace( '<i>', '').replace('</i>', '').replace('<br>', '') msg += shorten(description, info) image = json.get('bannerImage', None) if trailer: buttons = [[ InlineKeyboardButton("More Info", url=info), InlineKeyboardButton("Trailer 🎬", url=trailer) ]] else: buttons = [[InlineKeyboardButton("More Info", url=info)]] if image: try: update.effective_message.reply_photo( photo=image, caption=msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons)) except: msg += f" [〽️]({image})" update.effective_message.reply_text( msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons)) else: update.effective_message.reply_text( msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons))
def test_edit_message_reply_markup_without_required(self, bot): new_markup = InlineKeyboardMarkup([[InlineKeyboardButton(text='test', callback_data='1')]]) with pytest.raises(ValueError, match='Both chat_id and message_id are required when'): bot.edit_message_reply_markup(reply_markup=new_markup)
def manga(update: Update, context: CallbackContext): message = update.effective_message search = message.text.split(' ', 1) if len(search) == 1: update.effective_message.reply_text('Format : /manga < manga name >') return search = search[1] variables = {'search': search} json = requests.post(url, json={ 'query': manga_query, 'variables': variables }).json() msg = '' if 'errors' in json.keys(): update.effective_message.reply_text('Manga not found') return if json: json = json['data']['Media'] title, title_native = json['title'].get('romaji', False), json['title'].get( 'native', False) start_date, status, score = json['startDate'].get( 'year', False), json.get('status', False), json.get('averageScore', False) if title: msg += f"*{title}*" if title_native: msg += f"(`{title_native}`)" if start_date: msg += f"\n*Start Date* - `{start_date}`" if status: msg += f"\n*Status* - `{status}`" if score: msg += f"\n*Score* - `{score}`" msg += '\n*Genres* - ' for x in json.get('genres', []): msg += f"{x}, " msg = msg[:-2] info = json['siteUrl'] buttons = [[InlineKeyboardButton("More Info", url=info)]] image = json.get("bannerImage", False) msg += f"_{json.get('description', None)}_" if image: try: update.effective_message.reply_photo( photo=image, caption=msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons)) except: msg += f" [〽️]({image})" update.effective_message.reply_text( msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons)) else: update.effective_message.reply_text( msg, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons))
def accuweather(update, context): chat_id = update.effective_chat.id message = update.effective_message args = context.args if not args: return send_message( update.effective_message, tl(update.effective_message, "Masukan nama lokasinya untuk mengecek cuacanya!")) location = " ".join(args) if location.lower() == context.bot.first_name.lower(): send_message( update.effective_message, tl(update.effective_message, "Saya akan terus mengawasi di saat senang maupun sedih!")) context.bot.send_sticker(update.effective_chat.id, BAN_STICKER) return if True: url = "http://api.accuweather.com/locations/v1/cities/search.json?q={}&apikey={}".format( location, API_ACCUWEATHER) headers = {'Content-type': 'application/json'} r = requests.get(url, headers=headers) try: data = r.json()[0] except: return send_message( update.effective_message, tl(update.effective_message, "Maaf, lokasi tidak ditemukan 😞")) locid = data.get('Key') weatherlang = tl(update.effective_message, "weather_lang") urls = "http://api.accuweather.com/currentconditions/v1/{}.json?apikey={}&language={}&details=true&getphotos=true".format( locid, API_ACCUWEATHER, weatherlang) rs = requests.get(urls, headers=headers) datas = rs.json()[0] if datas.get('WeatherIcon') <= 44: icweather = "☁" elif datas.get('WeatherIcon') <= 42: icweather = "⛈" elif datas.get('WeatherIcon') <= 40: icweather = "🌧" elif datas.get('WeatherIcon') <= 38: icweather = "☁" elif datas.get('WeatherIcon') <= 36: icweather = "⛅" elif datas.get('WeatherIcon') <= 33: icweather = "🌑" elif datas.get('WeatherIcon') <= 32: icweather = "🌬" elif datas.get('WeatherIcon') <= 31: icweather = "⛄" elif datas.get('WeatherIcon') <= 30: icweather = "🌡" elif datas.get('WeatherIcon') <= 29: icweather = "☃" elif datas.get('WeatherIcon') <= 24: icweather = "❄" elif datas.get('WeatherIcon') <= 23: icweather = "🌥" elif datas.get('WeatherIcon') <= 19: icweather = "☁" elif datas.get('WeatherIcon') <= 18: icweather = "🌨" elif datas.get('WeatherIcon') <= 17: icweather = "🌦" elif datas.get('WeatherIcon') <= 15: icweather = "⛈" elif datas.get('WeatherIcon') <= 14: icweather = "🌦" elif datas.get('WeatherIcon') <= 12: icweather = "🌧" elif datas.get('WeatherIcon') <= 11: icweather = "🌫" elif datas.get('WeatherIcon') <= 8: icweather = "⛅️" elif datas.get('WeatherIcon') <= 5: icweather = "☀️" else: icweather = "" cuaca = "*{} {}*\n".format(icweather, datas.get('WeatherText')) cuaca += tl(update.effective_message, "*Suhu:* `{}°C`/`{}°F`\n").format( datas.get('Temperature').get('Metric').get('Value'), datas.get('Temperature').get('Imperial').get('Value')) cuaca += tl(update.effective_message, "*Kelembapan:* `{}`\n").format( datas.get('RelativeHumidity')) direct = "{}".format(datas.get('Wind').get('Direction').get('English')) direct = direct.replace("N", "↑").replace("E", "→").replace( "S", "↓").replace("W", "←") cuaca += tl( update.effective_message, "*Angin:* `{} {} km/h` | `{} mi/h`\n").format( direct, datas.get('Wind').get('Speed').get('Metric').get('Value'), datas.get('Wind').get('Speed').get('Imperial').get('Value')) cuaca += tl(update.effective_message, "*Tingkat UV:* `{}`\n").format(datas.get('UVIndexText')) cuaca += tl(update.effective_message, "*Tekanan:* `{}` (`{} mb`)\n").format( datas.get('PressureTendency').get('LocalizedText'), datas.get('Pressure').get('Metric').get('Value')) lok = [] lok.append(data.get('LocalizedName')) lok.append(data.get('AdministrativeArea').get('LocalizedName')) for x in reversed(range(len(data.get('SupplementalAdminAreas')))): lok.append( data.get('SupplementalAdminAreas')[x].get('LocalizedName')) lok.append(data.get('Country').get('LocalizedName')) teks = tl(update.effective_message, "*Cuaca di {} saat ini*\n").format(data.get('LocalizedName')) teks += "{}\n".format(cuaca) teks += tl(update.effective_message, "*Lokasi:* `{}`\n\n").format(", ".join(lok)) # try: # context.bot.send_photo(chat_id, photo=datas.get('Photos')[0].get('LandscapeLink'), caption=teks, parse_mode="markdown", reply_to_message_id=message.message_id, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="More info", url=datas.get('Link'))]])) # except: send_message(update.effective_message, teks, parse_mode="markdown", disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton(text="More info", url=datas.get('Link')) ]]))