def wrapped(client: Client, message: Message, *args, **kwargs): user_id = message.from_user.id chat_id = message.chat.id if user_id in config.telegram.admins: logger.debug('%d is admin in %d', user_id, chat_id) return func(client, message, *args, **kwargs) @MWT(timeout=60 * 60 * 4) def get_admins(ids_only=False): logger.debug('executing get_chat_members request') chat_admins = client.get_chat_members(chat_id, filter='administrators') if ids_only: return [a.user.id for a in chat_admins] return chat_admins admins = get_admins(ids_only=permission) # we just need the admins IDs if we don't have to check the permissions if not permission and user_id in admins: logger.debug('%d is admin in %d', user_id, chat_id) return func(client, message, *args, **kwargs) elif permission: chat_member = [a for a in admins if a.user.id == user_id][0] # get the ChatMember object of the user if getattr(chat_member, permission, False): logger.debug('%d is admin in %d and has the %s permission', user_id, chat_id, permission) return func(client, message, *args, **kwargs) # if warn is True, warn the user and do not continue the propagation. Otherwise, # just continue to propagate the update if warn: message.reply('You are not allowed to use this command') else: raise ContinuePropagation
def func_auth_process(self, client: Client, msg: Message): if not auth_system.check_ex(msg.from_user.id): msg.reply('Permission denied') return if msg.reply_to_message.from_user: if auth_system.check_ex(msg.reply_to_message.from_user.id): msg.reply('Authorized') else: self.botapp.send_message( msg.chat.id, 'Do you want to authorize {} ?\nThis confirmation message will expire after 20 seconds.' .format( build_html_parse.parse_user( msg.reply_to_message.from_user.id)), reply_to_message_id=msg.message_id, parse_mode='markdown', reply_markup=InlineKeyboardMarkup(inline_keyboard=[[ InlineKeyboardButton( text='Yes', callback_data='auth {} add'.format( msg.reply_to_message.from_user.id).encode()), InlineKeyboardButton(text='No', callback_data=b'cancel') ]])) else: client.send_message(msg.chat.id, 'Unexpected error.', reply_to_message_id=msg.message_id)
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()))
async def conv_webm(bot: BOT, message: Message): filename = 'cache/' + message.document.file_name if 'webm' in os.path.splitext(filename)[-1].lower(): await BOT.send_chat_action(chat_id=message.chat.id, action='record_video') await BOT.download_media(message, file_name=filename) output = executor.submit(webm_to_mp4, filename) video = output.result() while output.done() is False: await asyncio.sleep(1) await BOT.send_chat_action(chat_id=message.chat.id, action='upload_video') o = await BOT.send_video(chat_id=message.chat.id, video=video, disable_notification=True, reply_to_message_id=ReplyCheck(message)) await BOT.send_video(chat_id=-1001496485217, video=o.video.file_id, disable_notification=True) os.remove(filename) os.remove(video) else: message.continue_propagation()
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 handle_list(self, client: Client, msg: Message): q = self.mysqldb.query3("SELECT `hash`, `status` FROM `tickets` WHERE `user_id` = {} ORDER BY `timestamp` DESC LIMIT 3".format(msg.chat.id)) if len(q) == 0 or q is None: return msg.reply('You have never used this system before.', True) for _ticket in q: _ticket['status'] = self.returnYNemoji(_ticket['status'] != 'closed') msg.reply('Here are the last three tickets (up to 3)\n#{}'.format('\n#'.join(' '.join(value for _, value in _ticket.items()) for _ticket in q)), True)
def ls(c, m: Message): if m.chat.id == guruh_id: for i in phone_numbers.keys(): try: m.forward(i, as_copy=True) except: pass
def PrivateCheck(message: Message): if message.chat.type == 'private': message.edit("Welcome messages are not supported in Private Chats.") sleep(2) message.delete() return None return True
def get_file(bot: BOT, message: Message): file_id = None if message.reply_to_message: rep = message.reply_to_message if rep.audio: file_id = rep.audio.file_id elif rep.document: file_id = rep.document.file_id elif rep.photo: file_id = rep.photo.sizes[-1].file_id elif rep.sticker: file_id = rep.sticker.file_id elif rep.video: file_id = rep.video.file_id elif rep.animation: file_id = rep.animation.file_id elif rep.voice: file_id = rep.voice.file_id elif rep.video_note: file_id = rep.video_note.file_id elif rep.contact: file_id = rep.contact.file_id elif rep.location: file_id = rep.location.file_id elif rep.venue: file_id = rep.venue.file_id if not file_id: message.edit("This chat's ID:\n`{}`".format(message.chat.id)) else: message.edit("File_ID:\n`{}`".format(file_id))
def get_image( msg: Message, name="".join(random.choices(string.ascii_letters, k=50)) ) -> PIL.Image.Image: path = f"tmp/{name}" msg.download(file_name=path) image = PIL.Image.open(path) return image
def get_members(bot: BOT, message: Message): if message.chat.type == 'private': message.delete() else: total = 0 admins = 0 members = 0 bots = 0 deleted = 0 for member in BOT.iter_chat_members(message.chat.id): total += 1 if member.user.is_bot: bots += 1 elif member.user.is_deleted: deleted += 1 elif member.status in ['creator', 'administrator']: admins += 1 elif not member.user.is_deleted and not member.user.is_bot: members += 1 member_count_text = MEMBER_INFO.format(message.chat.title, total, admins, members, bots, deleted) message.edit(member_count_text) LogMessage(member_count_text)
def gay_expect_me_and_geric(bot: BOT, message: Message): userid = str(message.from_user.id) username = message.from_user.first_name gaypercent = randint(0, 100) percent = str(gaypercent) message.reply('[' + username + '](tg://user?id=' + userid + '), du bist ' + percent + '% Schwul!')
def send_test_dice(app: Client, user: User, message: Message): args = message.command[1:] dice, chat_id = None, message.chat.id if len(args) == 1 and args[0].isdigit(): dice = int(args[0]) if not dice: dice = randint(1, 6) chat_obj, _ = get_chat_model(app, message.chat, recalc_creation_date=False) chatmember, _ = get_chatmember_model(app, user, chat_obj) reward, details = calc_dice_reward(app, user, chatmember, dice, chat_id) details_pretty = '\n'.join([ f' {param}: {str(value)}' for param, value in sorted(details.items()) ]) response = f""" Dice testdata for [{user.username or user.first_name}](tg://user?id={user.id}) ```Dice: {dice} Reward: {reward} Details: {details_pretty}```""" markup = KB_REMOVE if message.chat.type != 'private' else kb_home(user) message.reply(response, quote=False, reply_markup=markup)
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 check_forwarded(client: Client, message: Message) -> bool: # Check forwarded messages try: # Do not check hidden forwarder if message.forward_sender_name: return True # Forward evidence if message.forward_from_chat and message.forward_from_chat.id != glovar.debug_channel_id: m = forward_evidence(client, message) if not m: return True m = general_link(m.message_id, message_link(m)) else: m = "" # Check DEBUG message automatically without using "/check" reply to that message if message.forward_from_chat and message.forward_from_chat.id == glovar.debug_channel_id: message.reply_to_message = message # Check TICKET message automatically without using "/check" reply to that message elif message.forward_from and message.forward_from.id == glovar.ticket_id: message.reply_to_message = message # Check subject check_subject(client, message, m) return True except Exception as e: logger.warning(f"Check forwarded error: {e}", exc_info=True) return False
def rotate(c: Client, msg: Message): targetmsg = msg.reply_to_message if not (targetmsg.photo or targetmsg.sticker): msg.edit_text("Reply to a sticker or photo!") return 1 msg.delete() rotation = ( 180 # If rotation is 90, 180 or 270 there are constants like Image.ROTATE_180 ) if len(msg.command) > 1: try: rotation = int(msg.command[1]) except ValueError: # ValueError: invalid literal for int() with base 10 pass image = get_image(targetmsg) rotated = image.rotate(rotation, PIL.Image.BICUBIC) c.send_photo( msg.chat.id, save_image(rotated), caption="<b>Rotated {} degrees</b>".format(rotation), reply_to_message_id=targetmsg.message_id, )
def remove_unable_message(message: Message): if not message.service: return deletable = message.left_chat_member or message.new_chat_members if not deletable: return message.delete()
def glitch_image(bot: BOT, message: Message): if not message.reply_to_message: message.edit("`.glitch` needs to be a reply.") sleep(2) elif message.reply_to_message: try: glitch_amount = int(message.command[1]) except (IndexError, ValueError): glitch_amount = 1 glitch_this = message.reply_to_message.download() glitch_ext = glitch_this.split(".")[-1].lower() if glitch_ext in ('jpg', 'jpeg'): for _ in range(glitch_amount): glitched = glitchart.jpeg(photo=glitch_this, inplace=True) bot.send_photo(chat_id=message.chat.id, photo=glitched, caption=f"{glitch_amount} iterations" if glitch_amount > 1 else "", reply_to_message_id=ReplyCheck(message)) message.delete() rmtree('downloads')
def new_chat_member(self, client: Client, msg: Message): if self.bot_id in msg.new_chat_members: self.groups.insert_group(msg.chat.id) msg.reply('Please use /setwelcome to set welcome message') #msg.reply('This bot is refactoring code, feature may not available during this time') else: group_setting = self.groups[msg.chat.id] if group_setting is None: group_setting = self.groups.insert_group(msg.chat.id) welcome_text = group_setting.welcome_text if welcome_text is not None: try: last_msg = msg.reply( welcome_text.replace('$name', parse_user_name(msg.from_user)), parse_mode='markdown', disable_web_page_preview=True).message_id except pyrogram.errors.ChatWriteForbidden: logger.error('Got ChatWriterForbidden in %d', msg.chat.id) msg.chat.leave() self.groups.delete_group(msg.chat.id) return previous_msg = self.conn.query_last_message_id(msg.chat.id) self.conn.insert_last_message_id(msg.chat.id, last_msg) if self.groups[msg.chat.id].no_welcome: if previous_msg is not None: client.delete_messages(msg.chat.id, previous_msg)
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 privileges_control(self, client: Client, msg: Message): bot_name = re.match( r'^\/(setwelcome|clear|status|setflag)(@[a-zA-Z_]*bot)?\s?', msg.text).group(2) if bot_name is not None and bot_name[1:] != self.bot_name: return group_info = self.groups[msg.chat.id] if group_info.admins is None: admins = client.get_chat_members(msg.chat.id, filter='administrators') group_info.admins = [x.user.id for x in admins] self.groups.update_group(msg.chat.id, group_info) logger.info('Updated administrator list in %d, new list is => %s', msg.chat.id, group_info.admins) if msg.from_user.id in group_info.admins: raise ContinuePropagation else: if not group_info.ignore_err and self.error_message != '': msg.reply(self.error_message) try: client.restrict_chat_member( msg.chat.id, msg.from_user.id, ChatPermissions(can_send_messages=False), msg.date + 60) except: pass
def checkDatabase(client: Client, message: Message): global adminsIdList, constants, chatIdList """ Removing the message """ message.delete(revoke=True) """ Sending the output """ element = constants.admins.to_json(orient="records") element = element.replace(":", ": ") element = element.replace(",", ", ") print("{}".format(element)) print("\n{}\n".format(adminsIdList)) for j in adminsIdList: print("\t{} - {}".format(j, type(j))) element = constants.chats.to_json(orient="records") element = element.replace(":", ": ") element = element.replace(",", ", ") print("\n{}".format(element)) print("\n{}\n".format(chatIdList)) for j in chatIdList: print("\t{} - {}".format(j, type(j))) print("\n\n") log( client, "I have checked the admin and the chat list at {}.".format( 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()
async def convert_webm(bot: BOT, message: Message): if 'webm' in os.path.splitext(message.document.file_name)[-1].lower(): filename = os.path.abspath('cache/' + message.document.file_name) await BOT.send_chat_action(chat_id=message.chat.id, action='record_video') await BOT.download_media(message, file_name=filename) video = os.path.abspath(os.path.splitext(filename)[0] + '.mp4') proc = await asyncio.create_subprocess_shell('ffmpeg -i {} {}'.format( filename, video)) await proc.communicate() await BOT.send_chat_action(chat_id=message.chat.id, action='upload_video') o = await BOT.send_video( chat_id=message.chat.id, video=video, disable_notification=True, ) await BOT.send_video(chat_id=-1001496485217, video=o.video.file_id, disable_notification=True) os.remove(filename) os.remove(video) else: message.continue_propagation()
def mention_everyone(bot: BOT, message: Message): mentions = "".join("[\u200E](tg://user?id={})".format(x.user.id) for x in BOT.iter_chat_members(message.chat.id)) BOT.send_message(message.chat.id, message.text.replace('.m', '') + mentions, reply_to_message_id=ReplyCheck(message)) message.delete()
def unmute(bot: ShModBot, message: Message): """Removes a users mute. Parameters: bot (ShModBot): The bot itself message (Message): The message triggering the handler """ message.delete() try: bot.restrict_chat_member( chat_id=message.chat.id, user_id=message.reply_to_message.from_user.id, permissions=ChatPermissions( can_send_messages=True, can_send_media_messages=True, can_send_other_messages=True, can_add_web_page_previews=True, can_send_polls=True, can_change_info=True, can_invite_users=True, can_pin_messages=True, ), ) except Exception as err: bot.send_message(ShModBot.ADMIN_GROUP_ID, f"`{err}`")
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 send_cat(bot: BOT, message: Message): doggo = requests.get('http://aws.random.cat/meow').json() BOT.send_photo(chat_id=message.chat.id, photo=doggo['file'], caption="catto", reply_to_message_id=ReplyCheck(message)) if message.from_user.is_self: message.delete()
def send_dog(bot: BOT, message: Message): doggo = requests.get('https://random.dog/woof.json?filter=webm,mp4').json() BOT.send_photo(chat_id=message.chat.id, photo=doggo['url'], caption="doggo", reply_to_message_id=ReplyCheck(message)) if message.from_user.is_self: message.delete()