def run(self): # Listen for updates while True: update = self.updates.poll() # This will block until an update is available triggers = [] if isinstance(update, Updates): for x in update.updates: if not isinstance(x,UpdateNewChannelMessage): continue if isinstance(x.message,MessageService): continue # We're only interested in messages to supergroups words = word_tokenize(x.message.message.lower()) # Avoid matching 'emacs' in 'spacemacs' and similar if 'emacs' in words and x.message.to_id.channel_id not in EMACS_BLACKLIST: triggers.append(('emacs',x.message)) if 'chrome' in words: triggers.append(('chrome',x.message)) if 'x files theme' == x.message.message.lower() and x.message.out: # Automatically reply to yourself saying 'x files theme' with the audio msg = x.message chan = InputPeerChannel(msg.to_id.channel_id,CHANNELS[msg.to_id.channel_id]) self.send_voice_note(chan,'xfiles.m4a',reply_to=msg.id) sleep(1) if '.shrug' in x.message.message.lower() and x.message.out: # Automatically replace '.shrug' in any message you # send to a supergroup with the shrug emoticon msg = x.message chan = InputPeerChannel(msg.to_id.channel_id,CHANNELS[msg.to_id.channel_id]) self(EditMessageRequest(chan,msg.id, message=msg.message.replace('.shrug','¯\_(ツ)_/¯'))) sleep(1)
def run(self): # Listen for updates while True: update = self.updates.poll( ) # This will block until an update is available triggers = [] if isinstance(update, Updates): for x in update.updates: if not isinstance(x, UpdateNewChannelMessage): continue if isinstance(x.message, MessageService): continue # We're only interested in messages to supergroups words = word_tokenize(x.message.message.lower()) # Avoid matching 'emacs' in 'spacemacs' and similar if 'emacs' in words and x.message.to_id.channel_id not in EMACS_BLACKLIST: triggers.append(('emacs', x.message)) if 'chrome' in words: triggers.append(('chrome', x.message)) if 'x files theme' == x.message.message.lower( ) and x.message.out: # Automatically reply to yourself saying 'x files theme' with the audio msg = x.message chan = InputPeerChannel(msg.to_id.channel_id, CHANNELS[msg.to_id.channel_id]) self.send_voice_note(chan, 'xfiles.m4a', reply_to=msg.id) sleep(1) if '.shrug' in x.message.message.lower() and x.message.out: # Automatically replace '.shrug' in any message you # send to a supergroup with the shrug emoticon msg = x.message chan = InputPeerChannel(msg.to_id.channel_id, CHANNELS[msg.to_id.channel_id]) self( EditMessageRequest(chan, msg.id, message=msg.message.replace( '.shrug', '¯\_(ツ)_/¯'))) sleep(1) for trigger in triggers: msg = trigger[1] chan = InputPeerChannel(msg.to_id.channel_id, CHANNELS[msg.to_id.channel_id]) log_chat = InputPeerUser(user_id=123456789, access_hash=987654321234567890) self.send_message( log_chat, "{} said {} in {}. Sending react {}".format( msg.from_id, msg.message, CHANNELNAMES[msg.to_id.channel_id], REACTS[trigger[0]][:20])) react = '>{}\n{}'.format(trigger[0], REACTS[trigger[0]]) self.invoke( SendMessageRequest(chan, react, reply_to_msg_id=msg.id)) sleep(1)
async def on_edit_preview(event, target): try: await borg( EditMessageRequest(peer=await event.get_input_chat(), id=target.id, no_webpage=bool(target.media), message=target.message, entities=target.entities)) except MessageNotModifiedError: # There was no preview to modify pass
async def handle_challenge_timeout(bot, delay, chat, user, bot_msg): global config, current_challenges await asyncio.sleep(delay) async with config_lock: group_config = config.get(str(chat.id), config['*']) async with cch_lock: del current_challenges['{chat}|{msg}'.format(chat=chat.id, msg=bot_msg)] try: # note that the arg name is 'reply_markup', not 'buttons' await bot( EditMessageRequest(message=group_config['msg_challenge_failed'], peer=chat, id=bot_msg, reply_markup=None)) except errors.BadRequestError: # it is very possible that the message has been deleted # so assume the case has been dealt by group admins, simply ignore it return None try: if group_config['challenge_timeout_action'] == 'ban': await bot( EditBannedRequest( chat, user, ChatBannedRights(until_date=None, view_messages=True))) elif group_config['challenge_timeout_action'] == 'kick': await bot( EditBannedRequest( chat, user, ChatBannedRights(until_date=None, view_messages=True))) await bot( EditBannedRequest(chat, user, ChatBannedRights(until_date=None))) else: # restrict # assume that the user is already restricted (when joining the group) pass except errors.ChatAdminRequiredError: # lose our privilege between villain joining and timeout pass if group_config['delete_failed_challenge']: await asyncio.create_task( safe_delete_message( bot, group_config['delete_failed_challenge_interval'], channel=chat, id=[bot_msg]))
async def reparse(event): old_entities = event.message.entities or [] parser = partial(parse, old_entities=old_entities) message, msg_entities = await borg._parse_message_text(event.raw_text, parser) if len(old_entities) >= len(msg_entities) and event.raw_text == message: return await borg(EditMessageRequest( peer=await event.get_input_chat(), id=event.message.id, message=message, no_webpage=not bool(event.message.media), entities=msg_entities )) raise events.StopPropagation
def edit(self, msg, force=False): while True: try: self.client.invoke( EditMessageRequest(get_input_peer(self.channel), self.msg.id, message=msg)) break except ValueError: self.client.disconnect() self.client.connect() except FloodWaitError as e: if not force: break print('flood error occurred, waiting...') sleep(e.seconds + 2)
async def on_edit_preview(event): await event.delete() target = await util.get_target_self_message(borg, event) if not target: return try: await borg( EditMessageRequest(peer=await event.get_input_chat(), id=target.id, no_webpage=bool(target.media), message=target.message, entities=target.entities)) except MessageNotModifiedError: # There was no preview to modify pass
def reparse(event): message, msg_entities = client._parse_message_text(event.text, 'md') if len(event.message.entities or []) == len(msg_entities) and event.raw_text == message: return request = EditMessageRequest( peer=event.input_chat, id=event.message.id, message=message, no_webpage=not bool(event.message.media), entities=msg_entities ) result = client(request) raise events.StopPropagation
async def my_e_handler(e): if '.xen ping' == e.raw_text: start=round(time.time() * 1000) pongmsg=await e.reply('Pong!') end=round(time.time() * 1000) msstartend=int(end) - int(start) await client(EditMessageRequest(peer=e.chat_id, id=pongmsg.id, message='Pong!\n' + str(msstartend) + 'ms')) elif '.msgid' == e.raw_text: await e.reply('There are ' + str(e.id + 1) + ' messages (including this one) in this chat') elif '.random' == e.raw_text: rannum = randint(0, 69420) await e.reply(str(rannum)) elif '.antispam' in e.raw_text: checkspam=str(e.raw_text[11:]) spamscore=str(antispam.score(checkspam)) spambool=str(antispam.is_spam(checkspam)) await e.reply('Spam results for `' + checkspam + '`\nScore: ' + spamscore + '\nIs Spam: ' + spambool)
async def reparse(event): message, msg_entities = await borg._parse_message_text(event.text, parse) # filter out entities that we don't generate old_entities = [] for entity in event.message.entities or []: if isinstance(entity, PARSED_ENTITIES): old_entities.append(entity) if len(old_entities) == len(msg_entities) and event.raw_text == message: return await borg( EditMessageRequest(peer=await event.input_chat, id=event.message.id, message=message, no_webpage=not bool(event.message.media), entities=msg_entities)) raise events.StopPropagation
async def handleEdit(event: events.MessageEdited.Event): editedMessageDb = echosDb.find_one({"reply_author": event.message.id}) if editedMessageDb != None: result = await client( GetMessagesRequestChannel(channel=event.input_chat, id=[editedMessageDb["reply_me"]])) if len(result.messages) < 1: # if message doesn't exist echosDb.delete_one( {"reply_author": editedMessageDb["reply_author"]}) else: myMessage = result.messages[0] await client( EditMessageRequest(peer=myMessage.peer_id, message=event.message.message, id=myMessage.id, media=myMessage.media, reply_markup=myMessage.reply_markup, entities=myMessage.entities, no_webpage=True))
def edit_message(msg: Message, text: str): EditMessageRequest(msg, str)
elif '#업데이트확인' in msg.message: try: url = urlopen( 'http://comic.naver.com/webtoon/list.nhn?titleId=119874&weekday=' ) html = url.read().decode('utf-8') url.close() spt = html.split( '<a href="/webtoon/detail.nhn?titleId=119874&no=' ) toon_id = spt[1].split('&')[0] update_date = spt[2].split( '<td class="num">')[1].split('</')[0] sleep(0.5) client.invoke( EditMessageRequest( get_input_peer(dest_channel.channel), msg.id, message= '< 업데이트 정보 >\n%s\nhttp://comic.naver.com/webtoon/detail.nhn?titleId=119874&no=%s&weekday=tue' % (update_date, toon_id))) except: client.invoke( EditMessageRequest( get_input_peer(dest_channel.channel), msg.id, message= '< 업데이트 정보 >\n일시적인 오류로 업데이트를 확인할 수 없습니다.')) client.disconnect()
def update_handler(update): global recent_reacts try: msg = update.message except AttributeError: # print(update, 'did not have update.message') return if isinstance(msg, MessageService): print(msg, 'was service msg') return # React to messages in supergroups and PMs if isinstance(update, UpdateNewChannelMessage): words = re.split('\W+', msg.message) for trigger, response in REACTS.items(): if len(recent_reacts[msg.to_id.channel_id]) > 3: # Silently ignore triggers if we've recently sent 3 reactions break if trigger in words: # Remove recent replies older than 10 minutes recent_reacts[msg.to_id.channel_id] = [ a for a in recent_reacts[msg.to_id.channel_id] if datetime.now() - a < timedelta(minutes=10) ] # Send a reaction client.send_message(msg.to_id, response, reply_to=msg.id) # Add this reaction to the list of recent actions recent_reacts[msg.to_id.channel_id].append(datetime.now()) if isinstance(update, UpdateShortMessage): words = re.split('\W+', msg) for trigger, response in REACTS.items(): if len(recent_reacts[update.user_id]) > 3: # Silently ignore triggers if we've recently sent 3 reactions break if trigger in words: # Send a reaction client.send_message(update.user_id, response, reply_to=update.id) # Add this reaction to the list of recent reactions recent_reacts[update.user_id].append(datetime.now()) # Automatically send relevant media when we say certain things # When invoking requests, get_input_entity needs to be called manually if isinstance(update, UpdateNewChannelMessage) and msg.out: if msg.message.lower() == 'x files theme': client.send_voice_note(msg.to_id, 'xfiles.m4a', reply_to=msg.id) if msg.message.lower() == 'anytime': client.send_file(msg.to_id, 'anytime.png', reply_to=msg.id) if '.shrug' in msg.message: client( EditMessageRequest(client.get_input_entity(msg.to_id), msg.id, message=msg.message.replace( '.shrug', r'¯\_(ツ)_/¯'))) if isinstance(update, UpdateShortMessage) and update.out: if msg.lower() == 'x files theme': client.send_voice_note(update.user_id, 'xfiles.m4a', reply_to=update.id) if msg.lower() == 'anytime': client.send_file(update.user_id, 'anytime.png', reply_to=update.id) if '.shrug' in msg: client( EditMessageRequest(client.get_input_entity(update.user_id), update.id, message=msg.replace('.shrug', r'¯\_(ツ)_/¯')))