def send_message(self, peer, message, no_web_page=False, PM=False, access_hash=None): msg_id = utils.generate_random_long() if not (PM is True): self.invoke( SendMessageRequest(peer=InputPeerChat(peer), message=message, random_id=msg_id, no_webpage=no_web_page)) else: if access_hash: self.invoke( SendMessageRequest(peer=InputPeerUser(peer, access_hash), message=message, random_id=msg_id, no_webpage=no_web_page)) else: print( "Access hash not provided. Could send message to InputPeerUser." ) return msg_id
async def send_blankx(e): usir = e.pattern_match.group(1)[:-1] skep = 7 + len(usir) ttxt = e.raw_text[skep:] f = ':\nUser: `' + usir + '`\nText:\n' + ttxt await e.edit('Sending' + f) thisisfine = True try: usir = int(usir) except: print('this is fine') try: await bot.send_message(await bot.get_input_entity(usir), message=ttxt) except: try: await bot.send_message(usir, message=ttxt) except: try: await bot(SendMessageRequest(peer=usir, message=ttxt)) except: try: await bot( SendMessageRequest(peer=bot.get_input_entity(usir), message=ttxt)) except: thisisfine = False if thisisfine == True: await e.edit('Sent' + f) else: await e.edit('Failed to send' + f)
async def send_message(self, entity, message, reply_to=None, entities=None, markdown=False, link_preview=True): entity = await self.get_input_entity(entity) if markdown: message, entities = parse_md(message) request = SendMessageRequest( peer=entity, message=message, entities=entities, no_webpage=not link_preview, reply_to_msg_id=self._get_message_id(reply_to) ) result = await self(request) if isinstance(result, UpdateShortSentMessage): return Message( id=result.id, to_id=entity, message=message, date=result.date, out=result.out, media=result.media, entities=result.entities ) return self._get_response_message(request, result)
def defenseTime(chatTarget): time.sleep(random.randint(1, 30)) client(SendMessageRequest(chatTarget, message="🛡Defend")) print("Sent defense order.") # Waiting 5 minutes for end of battle time.sleep(300)
def _reply_to(self, text, msg_id): new_id = telethon.helpers.generate_random_long() self._client.invoke( SendMessageRequest(self._peer, text, new_id, reply_to_msg_id=msg_id)) self._last_acion_date = datetime.datetime.now()
def send_messages(self, participant, messages, tempo): self.client.connect() for message in messages: self.client.invoke( SendMessageRequest(self.client.get_input_entity(participant), message)) #self.client.send_message(participant.id, message) time.sleep(tempo) self.client.disconnect()
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)
def send(self): _results = [] # Enviando menssagens conforme os dados coletados for data in self.data: _results.append( self.client( SendMessageRequest(self.peer, self.__formater(data)))) return _results
def send_message(self, input_peer, message, markdown=False, no_web_page=False): """Sends a message to the given input peer and returns the sent message ID""" if markdown: msg, entities = parse_message_entities(message) else: msg, entities = message, [] msg_id = utils.generate_random_long() self.invoke(SendMessageRequest(peer=input_peer, message=msg, random_id=msg_id, entities=entities, no_webpage=no_web_page)) return msg_id
def channelback(request): print('channelback'); # return render(request, 'admin.html') metadata = '' newState = '' chatId = '' if request.method == 'POST': print('POST channelback') metadata = request.POST.get('metadata', '') newState = request.POST.get('state', '') message = request.POST.get('message', '') parentId = request.POST.get('parent_id', '') recipientId = request.POST.get('recipient_id', '') metaJson = json.loads(metadata) api_id = metaJson['api_id'] api_hash = metaJson['api_hash'] phone = metaJson['phone_number'] username = metaJson['username'] parentSplit = parentId.split('-') client = TelegramClient(username, api_id, api_hash) client.connect() dialogs, entities = client.get_dialogs() for entity in entities: if not entity.bot: if "User(" in str(entity) : if entity.id == int(parentSplit[2]): peer = utils.get_input_user(entity) sendMessage = client(SendMessageRequest(peer, message)) chatId = parentSplit[0] + '-' + parentSplit[1] + '-' + parentSplit[2] + '-' + str(sendMessage.id) client.disconnect() else: print('NOT POST channelback') response_data = {} response_data['external_id'] = chatId response_data['allow_channelback'] = True return HttpResponse(json.dumps(response_data, ensure_ascii=False), content_type="application/json;charset=UTF-8")
def send_message_to_channel(msg: str) -> None: chash = 2860610687140429468 cid = 1113142718 channel = InputPeerChannel(cid, chash) client(SendMessageRequest(channel, msg))
def send_oldnine(client, usernameORphone, content=''): peer = client.get_input_entity(usernameORphone) # 可更换用户名@username或者手机号 if content != '': client(SendMessageRequest(usernameORphone, content)) peer = utils.get_input_peer(peer) print(peer)
def forayTime(chatTarget): time.sleep(random.randint(1, 10)) client(SendMessageRequest(chatTarget, message="/go")) print("Sent /GO order. ")
def message(self, iq): """ Обработчик входящих сообщений из XMPP :param iq: :return: """ jid = iq['from'].bare if iq['to'] == self.config['jid'] and iq[ 'type'] == 'chat': # Пишут транспорту if iq['body'].startswith('!'): self.process_command(iq) else: self.gate_reply_message( iq, 'Only commands accepted. Try !help for more info.') else: # Пишут в Telegram if jid in self.tg_connections and self.tg_connections[ jid].is_user_authorized(): if iq['body'].startswith('!'): # Команда из чата print('command received') if iq['to'].bare.startswith('u'): self.process_chat_user_command(iq) elif iq['to'].bare.startswith( 'g') or iq['to'].bare.startswith('s'): self.process_chat_group_command(iq) else: self.gate_reply_message(iq, 'Error.') else: # Обычное сообщение print('sent message') tg_id = int(iq['to'].node[1:]) tg_peer = None msg = iq['body'] reply_mid = None if msg.startswith('>'): # Проверка на цитирование msg_lines = msg.split('\n') matched = re.match(r'>[ ]*(?P<mid>[\d]+)[ ]*', msg_lines[0]).groupdict() if 'mid' in matched: # Если нашли ID сообщения, то указываем ответ reply_mid = int(matched['mid']) msg = '\n'.join(msg_lines[1:]) if iq['to'].bare.startswith('u'): # Обычный пользователь tg_peer = InputPeerUser( tg_id, self.tg_dialogs[jid]['users'][tg_id].access_hash) elif iq['to'].bare.startswith('g'): # Обычная группа tg_peer = InputPeerChat(tg_id) elif iq['to'].bare.startswith('s') or iq[ 'to'].bare.startswith('c'): # Супергруппа tg_peer = InputPeerChannel( tg_id, self.tg_dialogs[jid]['supergroups'] [tg_id].access_hash) if tg_peer: # Отправляем сообщение и получаем новый апдейт result = self.tg_connections[jid].invoke( SendMessageRequest(tg_peer, msg, generate_random_long(), reply_to_msg_id=reply_mid)) msg_id = None # Ищем ID отправленного сообщения if type(result) is Updates: # Супегруппа / канал for upd in result.updates: if type(upd) is UpdateMessageID: msg_id = upd.id elif type(result ) is UpdateShortSentMessage: # ЛС / Группа msg_id = result.id
# 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) f 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) if __name__ == "__main__": #TODO: this block could be moved to __init__ # You can create these text files using https://github.com/LonamiWebs/Telethon/wiki/Retrieving-all-dialogs with open('channels.txt','r') as f: # Format: channel_id access_hash #Channel Name lines = f.readlines() chans = [l.split(' #',1)[0].split(' ') for l in lines] CHANNELS = {int(c[0]):int(c[1]) for c in chans} # id:hash CHANNELNAMES = {int(l.split()[0]):l.split('#',1)[1].strip() for l in lines} #id:name with open('users','r') as f: # Format: [user_id, access_hash, 'username', 'Firstname Lastname'] lines = f.readlines() uss = [l.strip()[1:-1].split(',') for l in lines]