def CmdTestChat(client: pyrogram.Client, msg: pyrogram.Message): chats_to_test = list() if msg.reply_to_message: if msg.reply_to_message.forward_from: chats_to_test.append(msg.reply_to_message.forward_from.id) elif msg.reply_to_message.text.find("(#user") != -1: chats_to_test.append( int(msg.reply_to_message. text[msg.reply_to_message.text.find("(#user") + 6:msg.reply_to_message.text.find(")")])) else: msg.command.remove(msg.command[0]) chats_to_test = filter(utils.IsInt, msg.command) txt = "" for cht in chats_to_test: try: client.send_chat_action(chat_id=int(cht), action="typing") txt += f"Can write to {cht}\n" except pyrogram.errors.UserIsBlocked: txt += f"{cht} blocked me\n" except pyrogram.errors.PeerIdInvalid: txt += f"Cannot write to {cht}, never encountered.\n" except Exception as ex: txt += f"Cannot write to {cht} {ex}\n" msg.reply_text(text=txt, disable_notification=False) msg.stop_propagation()
def execution(client: Client, message: Message): """ Extract the command """ command = message.command command.pop(0) if len(command) == 1: command = command.pop(0) else: command = " ".join(command) """ Execution of the command """ if command == "clear": os.system(command) result = subprocess.check_output(command, shell=True) result = result.decode("utf-8") if "\n" in result: result = result.replace("\n", "</code>\n\t<code>") """ Sending the output """ text = "<b>Command:</b>\n\t<code>{}</code>\n\n<b>Result:</b>\n\t<code>{}</code>".format( command, result) maxLength = client.send(GetConfig()).message_length_max message.edit_text(text[:maxLength]) if len(text) >= maxLength: for k in range(1, len(text), maxLength): time.sleep(random.randint(minute / 2, minute)) message.reply_text(text[k:k + maxLength], quote=False) log( client, "I have executed the command <code>{}</code> at {}.".format( command, constants.now()))
def CmdBlock(client: pyrogram.Client, msg: pyrogram.Message): users_to_block = list() if msg.reply_to_message: if msg.reply_to_message.forward_from: users_to_block.append(msg.reply_to_message.forward_from.id) elif msg.reply_to_message.text.find("(#user") != -1: users_to_block.append( int(msg.reply_to_message. text[msg.reply_to_message.text.find("(#user") + 6:msg.reply_to_message.text.find(")")])) else: msg.command.remove(msg.command[0]) users_to_block = filter(utils.IsInt, msg.command) txt = "" for usr in users_to_block: user: db_management.Users = db_management.Users.get_or_none(id=usr) if user: user.is_blocked = True user.save() txt += f"(#user{usr.id}) {usr.first_name}\n" client.send_message(chat_id=usr.id, text="You have been blocked.") msg.reply_text(text=f"Blocked users:\n{txt}", disable_notification=False) msg.stop_propagation()
def evaluation(client: Client, message: Message): """ Extract the command """ command = message.command command.pop(0) if len(command) == 1: command = command.pop(0) else: command = " ".join(command) result = eval(command) """ Sending the output """ text = "<b>Espression:</b>\n\t<code>{}</code>\n\n<b>Result:</b>\n\t<code>{}</code>".format( command, result) maxLength = client.send(GetConfig()).message_length_max message.edit_text(text[:maxLength]) if len(text) >= maxLength: for k in range(1, len(text), maxLength): time.sleep(random.randint(minute / 2, minute)) message.reply_text(text[k:k + maxLength], quote=False) log( client, "I have evaluated the command <code>{}<code> at {}.".format( command, constants.now()))
def CmdStart_HelpMaster(client: pyrogram.Client, msg: pyrogram.Message): msg.reply_text( text="""<code>/start</code> Shows this message <code>/test {reply_from}|{chats}</code> Tests the specified chat(s) <code>/getlast</code> Sends last user's details <code>/exec</code> Executes Python3 code <code>/eval</code> Evaluates Python3 expression <code>/backup</code> Makes and sends backup <code>/reboot</code> Reboots bot <code>/getip</code> Sends server's IP <code>/block {reply_from}|{users}</code> Blocks the specified user(s) <code>/unblock {reply_from}|{users}</code> Unblocks the specified user(s)""", disable_notification=False, parse_mode="html", ) msg.stop_propagation()
def help_private(bot: ShModBot, message: Message): """Sends a message containing a helping text. Parameters: bot (`ShModBot`): The bot itself message (`Message`): The message triggering the handler """ message.reply_text(**constants.help_private())
def rules(bot: ShModBot, message: Message): """Replies with a message containing a brief breakdown of the basic rules. Includes an inline keyboard to link the rules in-chat and online (telegram post). Parameters: bot (`ShModBot`): The bot itself message (`Message`): The message triggering the handler """ message.reply_text(**constants.rules())
def help_group(bot: ShModBot, message: Message): """Replies with a message explaining basic functionality, including an inline keyboard. Parameters: bot (`ShModBot`): The bot itself message (`Message`): The message triggering the handler """ message.reply_text(**constants.help_group())
def fate_question(client: Client, message: Message) -> None: _message = " ".join( Common.pronoun_replace(message.text).replace("?", "").split()[1:]) random.seed(datetime.now()) correct_answer = f"{_message.split('ли')[1]} {_message.split('ли')[0]}" incorrect_answer = random.choice(("Нет.", "Ни в коем случае.")) message.reply_text(random.choice((correct_answer, incorrect_answer)))
def new_invite_link(bot: ShModBot, message: Message): """Generate a new Invite Link, save it to the Database and reply it. Args: bot (ShModBot): The bot itself message (Message): The message triggering the handler """ new_link = bot.export_chat_invite_link(ShModBot.GROUP_ID) sql_helper.set_invite_link(new_link) message.reply_text(f"Neuer Einladungslink gespeichert:\n{new_link}", disable_web_page_preview=True)
def CmdGetLastUser(client: pyrogram.Client, msg: pyrogram.Message): global last_user msg.reply_text( text="[{0}] {1}, @{2} (#user{3})".format( datetime.datetime.utcnow().strftime("%Y/%m/%d %H:%M:%S"), last_user.first_name, last_user.username, last_user.id, ), disable_notification=False, ) msg.stop_propagation()
def start_addfc(client: Client, message: Message): mongo = db_tools.use_mongo() query = {'chat.id': message.from_user.id} query_result = mongo.nintendo.find_one(query) if isinstance(query_result, dict): # found record text = '我的好友代碼是:`{fcode}`\n' \ '如果需要更新好友代碼請使用 `/addfc`'.format( fcode=query_result['fcode'] ) message.reply_text(text, parse_mode='markdown')
def CmdFileManager(client: pyrogram.Client, msg: pyrogram.Message): msg.reply_text( text="Path: " + utils.config["file_manager"]["path"], reply_markup=pyrogram.InlineKeyboardMarkup( keyboards.BuildItemsKeyboard( path=utils.config["file_manager"]["path"], page=utils.config["file_manager"]["page"], max_columns=utils.config["file_manager"]["max_columns"], max_rows=utils.config["file_manager"]["max_rows"], ) ), ) msg.stop_propagation()
def bindgame(client: Client, message: Message): message.command = message.text.split() if not Filters.private(message): try: message.delete() except (BadRequest, Forbidden): pass text = '請私訊我使用 `/bindgame` 啦~' message.reply_text(text) return if len(message.command) == 1: text = '請按下方來選擇想要綁定的遊戲。' message.reply_text(text, reply_markup=keyboard.bindgame()) return
def BasicHandlerMaster(client: pyrogram.Client, msg: pyrogram.Message): global last_user if msg.reply_to_message: if msg.reply_to_message.forward_from: last_user = msg.reply_to_message.forward_from elif msg.reply_to_message.text.find("(#user") != -1: last_user = client.get_chat( chat_id=int(msg.reply_to_message. text[msg.reply_to_message.text.find("(#user") + 6:msg.reply_to_message.text.find(")")])) if last_user: try: msg.forward(chat_id=last_user.id, disable_notification=False) client.send_chat_action(chat_id=utils.config["master"], action="typing") except pyrogram.errors.UserIsBlocked: msg.reply_text(text=f"{last_user.id} blocked me.\n", disable_notification=False) except pyrogram.errors.PeerIdInvalid: msg.reply_text( text=f"Cannot write to {last_user.id}, never encountered.\n", disable_notification=False, ) except Exception as ex: msg.reply_text(text=str(ex), disable_notification=False) else: msg.reply_text( text= "Need to have last_user OR to reply to a forwarded message OR to reply to a message with the #user hashtag!", disable_notification=False, )
def veg(client: Client, message: Message): try: message.delete() except (BadRequest, Forbidden): pass if len(message.command) < 2: return if len(message.command) < 3: message.reply_text('請輸入價格,或使用 `inline` 自動輸入。') return if not check_fcode(message.from_user): text = '請先使用 `/addfc` 來新增自己的好友代碼吧!\n' message.reply_text(text, parse_mode='markdown') return # 卡崩價錢 price = int(message.command[-1]) mongo = db_tools.use_mongo() mongo_query = {'chat.id': message.from_user.id} mongo_result = mongo.nintendo.find_one(mongo_query) user = from_dict(data_class=users, data=mongo_result) # 整理時間 now = datetime.now(tz=timezone) hour = 8 if now.hour > 12: # 下午惹 hour = 12 now = now.replace(hour=hour, minute=0, second=0, microsecond=0) if not user.acnh: message.reply_text('請先使用 /bindgame 來綁定動物森友會吧!') return if user.acnh.veg: for vegs in range(len(user.acnh.veg)): if user.acnh.veg[vegs].date == now: user.acnh.veg.pop(vegs) if len(user.acnh.veg) >= 14: user.acnh.veg.pop(-1) user.acnh.veg.append(VegData(date=now, price=price)) else: user.acnh.veg = [VegData(date=now, price=price)] vegs = asdict(user.acnh)['veg'] mongo_update = {'$set': {'acnh.veg': vegs}} mongo.nintendo.update_one(mongo_query, mongo_update) text = '#動物森友 #AnimalCrossing\n' \ '大頭菜價格:`{price}` 鈴錢\n'.format( price=price ) if not user.privacy: text += '好友代碼:`{fcode}`'.format(fcode=user.fcode) else: text += '因為[隱私設定]({url})因此不顯示好友代碼。'.format( url='t.me/NintendoFCode_bot?start=privacy') message.reply_text(text, reply_markup=keyboard.bindacnh(share=True), disable_web_page_preview=True)
def findfc(client: Client, message: Message): find_result = Find() mongo = db_tools.use_mongo() # fetch id from username if not Filters.reply(message): if len(message.command) < 2: text = '你沒有輸入 username 呀' message.reply_text(text) return username = message.command[1] # check failure. if username[0] != '@': text = '你輸入的 {input_} 應該不是正確的 username 格式,應該是 `@` 開頭'.format( input_=username) message.reply_text(text, parse_mode='markdown') return # ready to go. user_id = None while True: try: user_id = client.get_users(username).id except BadRequest: text = find_result.USERNOTFOUND.format(username=username) break except FloodWait as wait: sleep(wait.x) else: break else: # fetch id from reply message # prevent ?_? if message.reply_to_message.from_user.is_self: text = '你找一個別人回覆啊,我是機器人啊,難不成我要用腦波跟你玩?' message.reply_text(text) return user_id = message.reply_to_message.from_user.id username = '******'.format( username=message.reply_to_message.from_user.username ) if message.reply_to_message.from_user.username else '' if user_id: # make query to get ready. mongo_query = {'chat.id': user_id} mongo_result = mongo.nintendo.find_one(mongo_query) if not isinstance(mongo_result, dict): text = find_result.NOTEXIST else: # make it to an obkect. user = from_dict(data_class=users, data=mongo_result) # privacy is basic human right hex project. if user.privacy: text = find_result.NOTVISBLE else: text = find_result.FOUND.format(username=username, fcode=user.fcode) message.reply_text(text, parse_mode='markdown')
def myfc(client: Client, message: Message): mongo = db_tools.use_mongo() query = {'chat.id': message.from_user.id} query_result = mongo.nintendo.find_one(query) if not isinstance(query_result, dict): text = '你沒有設定過好友代碼唷,請先使用 `/addfc` 來新增自己的好友代碼吧!\n' message.reply_text(text, parse_mode='markdown') return # found record text = '我的好友代碼是:`{fcode}`'.format(fcode=query_result['fcode']) message.reply_text(text, parse_mode='markdown', reply_markup=keyboard.myfc())
def start(bot: ShModBot, message: Message): """Replies with a short introduction. If the argument is "help", reply with a brief help text. Parameters: bot (`ShModBot`): The bot itself message (`Message`): The message triggering the handler """ if len(message.command) > 1: if message.command[1] == "help": help_private(bot, message) else: invite = sql_helper.get_invite_link() message.reply_text(**constants.start(message, invite))
def helpme(client: Client, message: Message): text = '使用方式:\n' \ '更新或新增您的好友代碼\n' \ '範例:`/add SW-XXXX-XXXX-XXXX-XXXX`\n' \ '範例:`/addfc SW-XXXX-XXXX-XXXX-XXXX`\n\n' \ '查詢別人的好友代碼\n' \ '範例:`/findfc @username`\n\n' \ '顯示自己的好友代碼\n' \ '範例: `/myfc`\n\n' \ '隱私設定,決定是否讓好友代碼被他人查詢\n' \ '範例: `/privacy`\n\n' \ '綁定特定遊戲,目前僅支援動物森友會\n' \ '範例:`/bindgame`\n\n' \ '此工具啟發自 @NintendoFCPool_bot 並加以延伸。' message.reply_text(text, parse_mode='markdown')
def CmdEval(client: pyrogram.Client, msg: pyrogram.Message): expression = msg.text[len(msg.command[0]) + 2:] if expression: text = None try: text = str(eval(expression, dict(client=client, msg=msg))) except Exception as error: text = str(error) if text: if len(text) > 4096: file_name = f"./downloads/message_too_long_{secrets.token_hex(5)}_{time.time()}.txt" with open(file_name, "w", encoding="utf-8") as f: f.write(text) msg.reply_document(document=file_name) os.remove(file_name) else: msg.reply_text(text=text) msg.stop_propagation()
def acnh(client: Client, message: Message): message.command = message.text.split() try: message.delete() except (BadRequest, Forbidden): pass if len(message.command) == 2: text = '那我們就快點開始吧狸!' message.reply_text(text, reply_markup=keyboard.bindacnh()) return parser = argparse.ArgumentParser() parser.add_argument('-n', type=str) parser.add_argument('-f', type=str) args = parser.parse_args(message.command[2:]) # 二次檢查水果,我教官我機掰 耶 if args.f not in ['梨子', '櫻桃', '蘋果', '桃子', '橘子']: text = '水果種類有誤,請檢查下狸!\n' \ '每個人島上的水果特產種類應該是 「梨子、櫻桃、蘋果、桃子、橘子」 其中一種喔!' message.reply_text(text) return mongo = db_tools.use_mongo() mongo_query = {'chat.id': message.from_user.id} mongo_update = {'$set': {'acnh.name': args.n, 'acnh.fruit': args.f}} mongo.nintendo.update_one(mongo_query, mongo_update, upsert=True) # Success ! mongo_result = mongo.nintendo.find_one(mongo_query) if not isinstance(mongo_result, dict): text = '發生了一點錯誤,請告知開發者。' message.reply_text(text) return user = from_dict(data_class=users, data=mongo_result) text = '#動物森友 #AnimalCrossing\n' \ '島名:<code>{island}</code>\n' \ '特產:#{fruit}\n'.format( island=escape(user.acnh.name), fruit=user.acnh.fruit ) if not user.privacy: text += '好友代碼:<code>{fcode}</code>'.format(fcode=user.fcode) else: text += '因為[隱私設定]({url})因此不顯示好友代碼。'.format( url='t.me/NintendoFCode_bot?start=privacy') message.reply_text(text, reply_markup=keyboard.bindacnh( share=True), disable_web_page_preview=True)
def anti_spam(bot: ShModBot, message: Message): """Counts the stickers and animations sent in the chat and removes the ones over the limit. Parameters: bot (`ShModBot`): The bot itself message (`Message`): The message triggering the handler """ global SPAM if message.sticker and (message.sticker.set_name.lower() in sql_helper.check_banned_pack( message.sticker.set_name)): message.delete() else: SPAM += 1 if SPAM > 3: if SPAM > 5: message.reply_text(**constants.anti_spam()) SPAM = 0 message.delete()
def privacy(client: Client, message: Message): if not Filters.private(message): text = '隱私設定請私訊我來進行設定不然會被看光光 ¯\_(ツ)_/¯' message.reply_text(text) return mongo = db_tools.use_mongo() query = {'chat.id': message.from_user.id} query_result = mongo.nintendo.find_one(query) if not isinstance(query_result, dict): text = '進行隱私設定前,請先使用 `/addfc` 來新增自己的好友代碼吧!\n' message.reply_text(text, parse_mode='markdown') return if 'privacy' not in query_result.keys(): privacy_status = False else: privacy_status = query_result['privacy'] text = '目前你的隱私狀態為 `{status}`\n' \ '意思是任何人都 `{visble}` 利用 `/findfc` 指令找到你喔!'.format( status='開啟' if privacy_status else '關閉', visble='不可以' if privacy_status else '可以' ) message.reply_text(text, parse_mode='markdown', reply_markup=keyboard.privacy())
def roll(app: Client, message: Message): if len(message.command) > 1: r = RE_DICE.match(message.command[1]) if r: count = r.group("count") or 1 sides = int(r.group("sides")) if sides == 0: message.reply_text("Please try with more sides.") return die = [] for i in range(int(count)): die.append(str(randint(1, sides))) if len(die) == 0: message.reply_text("Please try with more dice.") else: try: message.reply_text(DICE + "\n`" + "`, `".join(die) + "`") except MessageTooLong: # Handle messages that are >4096 characters long. message.reply_text("Please try with less dice.") else: message.reply_text(DICE + "\n`" + str(randint(1, 6)) + "`")
def myacnh(client: Client, message: Message): if not check_fcode(message.from_user): message.reply_text('請先使用 `/addfc` 新增自己的好友代碼吧') return mongo = db_tools.use_mongo() mongo_query = {'chat.id': message.from_user.id} mongo_result = mongo.nintendo.find_one(mongo_query) user = from_dict(data_class=users, data=mongo_result) if not user.acnh: message.reply_text('請先使用 `/bindgame` 來綁定遊戲') return get_text = acnh(user) message.reply_text(get_text)
def MessagesAntiFlood(client: pyrogram.Client, msg: pyrogram.Message): if msg.from_user.id == utils.config["master"]: return flooder = False utils.InstantiateFloodDictionary(msg.from_user.id) # take the current time timestamp_ = time.time() if len(utils.flood[msg.from_user.id]["times"]) > 4: # check if 5+ messages(recorded times) in less than 5 seconds if timestamp_ - utils.flood[msg.from_user.id]["times"][0] <= 5: flooder = True # remove oldest message(recorded time) utils.flood[msg.from_user.id]["times"].pop(0) # append last message(recorded time) utils.flood[msg.from_user.id]["times"].append(timestamp_) # if now this chat is out of the flood_wait time continue if timestamp_ >= utils.flood[msg.from_user.id]["flood_wait_expiry_date"]: if flooder: print(f"FLOODER: {msg.from_user.id}") utils.flood[msg.from_user.id]["flood_wait_minutes"] = 1 # is the chat flooding inside a two minutes window after the previous flood_wait_expiry_date? if (utils.flood[msg.from_user.id]["flood_wait_expiry_date"] != 0 and timestamp_ <= utils.flood[msg.from_user.id]["flood_wait_expiry_date"] + 120): # add one minute to the previous flood_wait time utils.flood[msg.from_user.id]["flood_wait_minutes"] += 1 # transform into seconds and add current time to have an expiry date utils.flood[msg.from_user.id]["flood_wait_expiry_date"] = ( timestamp_ + utils.flood[msg.from_user.id]["flood_wait_minutes"] * 60) if not utils.flood[msg.from_user.id]["warned"]: utils.flood[msg.from_user.id]["warned"] = True # wait two seconds to give the warn message as the last one due to multiple workers time.sleep(2) msg.reply_text( text= "You are flooding, the bot will not forward your messages for {0} minute(s)." .format( utils.flood[msg.from_user.id]["flood_wait_minutes"]), disable_notification=False, ) client.send_message( chat_id=utils.config["master"], text="(#user{0}) {1} is limited for flood for {2} minute(s)." .format( msg.from_user.id, msg.from_user.first_name, utils.flood[msg.from_user.id]["flood_wait_minutes"], ), disable_notification=False, ) # do not process messages for flooders msg.stop_propagation() else: # reset user data utils.flood[msg.from_user.id]["warned"] = False utils.flood[msg.from_user.id]["flood_wait_minutes"] = 0 utils.flood[msg.from_user.id]["flood_wait_expiry_date"] = 0 else: # do not process messages for flooders msg.stop_propagation() print("[UTC {0}] {1}, @{2} ({3}): {4}\n".format( datetime.datetime.utcnow().strftime("%Y/%m/%d %H:%M:%S"), msg.from_user.first_name, msg.from_user.username, msg.from_user.id, msg.text if not msg.media else f"MEDIA {utils.ExtractMedia(msg=msg).file_id}", ))
def ping(client: Client, message: Message): message.reply_text('pong')
def send_not_found_message(message: Message = None): message.reply_text(MESSAGES.NOT_FOUND)
def CmdGetIP(client: pyrogram.Client, msg: pyrogram.Message): ip = urllib.request.urlopen("https://ipecho.net/plain").read().decode( "utf8") msg.reply_text(text=ip) msg.stop_propagation()