def telgram (): try: #receiver = InputPeerUser(788783751,-1972388975124423645) receiver1 = InputPeerUser(599782063,-6324027267714872446) receiver2 = InputPeerUser(529392635,-6354106180302249604) #client.send_message(receiver, 'A(s) porta(s) '+ str (a) +' \npara o endereço '+ endrrr +' \nestá '+ doorime + '\nVERIFIQUE AS REGRAS DE FIREWALL !!!', parse_mode='html') client.send_message(receiver1, 'A(s) porta(s) '+ str (a) +' \npara o endereço '+ endrrr +' \nestá '+ doorime + '\nVERIFIQUE AS REGRAS DE FIREWALL !!!', parse_mode='html') client.send_message(receiver2, 'A(s) porta(s) '+ str (a) +' \npara o endereço '+ endrrr +' \nestá '+ doorime + '\nVERIFIQUE AS REGRAS DE FIREWALL !!!', parse_mode='html') except Exception as e: print(e)
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
def remove_member(client, group): dem = 0 try: channel = client.get_entity(group.username) with open('data_remove/user/' + phone + "_" + str(group.id) + '.json', 'r', encoding='utf-8') as f: users = json.loads(f.read()) print(len(users)) if len(users) > 0: for user in users: try: user_to_ban = InputPeerUser(int(user['user_id']), int(user['access_hash'])) client( EditBannedRequest( channel, user_to_ban, ChatBannedRights(until_date=None, view_messages=True))) dem += 1 if dem >= 150: break except: print("Error remove_member for user") except: print("Error remove_member channel")
async def get_user(user: Dict, client: Optional[TelegramClient] = None): if user["username"] == "" or client is None: receiver = InputPeerUser(user["id"], user["access_hash"]) else: receiver = await client.get_input_entity(user["username"]) return receiver
def send_message(message): # Create a telegram session and assign it to a variable client client = TelegramClient('session', api_id, api_hash) client.connect() # In case of script ran first time it will ask either to input token or otp sent to number or sent or your telegram id if not client.is_user_authorized(): client.send_code_request(phone_number) # Signing in the client client.sign_in(phone_number, input('Enter the code: ')) try: for receiver in receivers: # Set receiver user_id and access_hash # To get userid and access hash: client.get_input_entity('@username') receiverUser = InputPeerUser(receiver['user_id'], receiver['access_hash']) # Send message using telegram client client.send_message(receiverUser, message) except Exception as e: # there may be many error coming in while like peer error, wwrong access_hash, flood_error, etc print(e) # Disconnecting the telegram session client.disconnect()
async def admem(event): xx = await edit_or_reply(event, "**Proses Menambahkan** `0` **Member**") chat = await event.get_chat() users = [] with open("members.csv", encoding="UTF-8") as f: rows = csv.reader(f, delimiter=",", lineterminator="\n") next(rows, None) for row in rows: user = {"id": int(row[0]), "hash": int(row[1])} users.append(user) n = 0 for user in users: n += 1 if n % 30 == 0: await xx.edit( f"**Sudah Mencapai 30 anggota, Tunggu Selama** `{900/60}` **menit**" ) await asyncio.sleep(900) try: userin = InputPeerUser(user["id"], user["hash"]) await event.client(InviteToChannelRequest(chat, [userin])) await asyncio.sleep(random.randrange(5, 7)) await xx.edit(f"**Proses Menambahkan** `{n}` **Member**") except TypeError: n -= 1 continue except UserAlreadyParticipantError: n -= 1 continue except UserPrivacyRestrictedError: n -= 1 continue except UserNotMutualContactError: n -= 1 continue
async def admem(event): x = await eor(event, "`Adding 0 members...`") chat = await event.get_chat() client = event.client users = [] with open("members.csv", encoding="UTF-8") as f: rows = csv.reader(f, delimiter=",", lineterminator="\n") next(rows, None) for row in rows: user = {'id': int(row[0]), 'hash': int(row[1])} users.append(user) n = 0 for user in users: n += 1 if n % 30 == 0: await eor(x, f"`Reached 30 members, sleeping for {900/60} minutes`") await asyncio.sleep(900) try: userin = InputPeerUser(user['id'], user['hash']) await client(InviteToChannelRequest(chat, [userin])) await asyncio.sleep(random.randrange(5, 7)) await eor(x, f"`Adding {n} members...`") except TypeError: n -= 1 continue except UserAlreadyParticipantError: n -= 1 continue except UserPrivacyRestrictedError: n -= 1 continue except UserNotMutualContactError: n -= 1 continue
def send_document(self, path, to, caption, first_name, last_name=None): contactModel = self.get_or_create_new_contact(to, first_name, last_name=last_name) if contactModel is None: return None peer_user = InputPeerUser(int(contactModel.user_id), int(contactModel.access_hash)) logging.info('Uploading {}...'.format(path)) input_file = self.upload_file( path, progress_callback=self.upload_progress_callback) # After we have the handle to the uploaded file, send it to our peer msg_id = self.send_document_file(input_file, peer_user, caption=caption) logging.debug('Document sent!') logging.info('Send message id {}'.format(msg_id)) # TO DO : remove file if uploaded successfully to telegram try: os.remove(path) except OSError as e: logging.warning( "Cannot remove document downloaded file {} : ".format( path, str(e))) return msg_id
async def sendMessageToAll(self, message): users = self.userStore.getAllActiveUsers() for u in users: peer = InputPeerUser(u[0], u[1]) try: await self.bot.send_message(peer, message, parse_mode="html") except UserIsBlockedError: self.userStore.removeUserFromDB(u[0], u[1])
async def handle_message(evt: events.NewMessage.Event) -> None: if '*' in allowed_user and not evt.is_private: return if not (str(evt.from_id) in allowed_user and str(evt.chat_id) in allowed_user) and '*' not in allowed_user: log.info(f'user {evt.from_id} or {evt.chat_id} not allowed to use this bot') if evt.is_private: await evt.delete() return if str(evt.message.message).startswith('/del') and evt.reply_to_msg_id is not None: if bool(int(evt.is_channel)) and bool(int(evt.is_group)): peer = InputPeerChat(chat_id=int(evt.chat_id)) else: if bool(int(evt.is_group)): peer = InputPeerChat(chat_id=int(evt.chat_id)) elif bool(int(evt.is_channel)): peer = InputPeerChannel(channel_id=int(evt.chat_id), access_hash=0) else: peer = InputPeerUser(user_id=int(evt.chat_id), access_hash=0) c = cast(Message, await client.get_messages(entity=peer, ids=evt.reply_to_msg_id)) me = await client.get_me() reply_msg = cast(Message, await c.get_reply_message()) log.debug(f'msg_from={c.from_id},evt_from={evt.from_id},c is reply={c.is_reply}' f',reply_msg_from={reply_msg.from_id if reply_msg is not None else 0}') if c.from_id == evt.from_id or (c.from_id == me.id and c.is_reply): if (reply_msg is not None and reply_msg.from_id == evt.from_id) or reply_msg is None: await client.delete_messages(evt.input_chat, [evt.reply_to_msg_id]) await evt.delete() else: if not evt.file: log.info('not evt.file') await evt.delete() return try: ret = get_media_meta(evt.media) if ret[0] and ret[1] and ret[2] <= max_file_size: middle_x = StringCoder.encode( f"{evt.chat_id}|{evt.id}|{1 if evt.is_group else 0}|{1 if evt.is_channel else 0}") log.debug(f"{evt.chat_id}|{evt.id}|{1 if evt.is_group else 0}|{1 if evt.is_channel else 0}") # url = public_url / str(pack_id(evt)) / get_file_name(evt) url = link_prefix / middle_x / get_file_name(evt) await evt.reply(f'[{url}]({url})') log.debug(f'Link to {evt.id} in {evt.chat_id}: {url}') else: if admin_id == evt.from_id and ret[0]: log.debug('admin usage') middle_x = StringCoder.encode( f"{evt.chat_id}|{evt.id}|{1 if evt.is_group else 0}|{1 if evt.is_channel else 0}") log.debug(f"{evt.chat_id}|{evt.id}|{1 if evt.is_group else 0}|{1 if evt.is_channel else 0}") # url = public_url / str(pack_id(evt)) / get_file_name(evt) url = link_prefix / middle_x / get_file_name(evt) await evt.reply(f'[{url}]({url})') log.debug(f'Link to {evt.id} in {evt.chat_id}: {url}') else: log.info('non-admin can not serve other than image') await evt.delete() except Exception as exp: await evt.reply(str(exp)) pass
def get_input_peer(entity): """Gets the input peer for the given "entity" (user, chat or channel). Returns None if it was not found""" if isinstance(entity, User): return InputPeerUser(entity.id, entity.access_hash) if isinstance(entity, Chat): return InputPeerChat(entity.id) if isinstance(entity, Channel): return InputPeerChannel(entity.id, entity.access_hash)
async def load_users(user_ids): return [ InputPeerUser(user_id=user['_id'], access_hash=user['access_hash']) for user in await users.find({ '_id': { '$in': user_ids } }).to_list(None) ]
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 my_event_handler(event): chat = await client.get_input_entity('Shit') current_sentence = event.raw_text print(event.message.to_id.chat_id) print(event) if event.message.to_id.chat_id == 340126983: if banned_word in current_sentence: await client.send_message( InputPeerUser(event.message.from_id, contact_list[event.message.from_id]), error_sentence)
def unpack_id(file_id: int) -> Tuple[TypeInputPeer, int]: is_group = file_id & group_bit is_channel = file_id & channel_bit chat_id = file_id >> chat_id_offset & pack_bit_mask msg_id = file_id >> msg_id_offset & pack_bit_mask if is_channel: peer = InputPeerChannel(channel_id=chat_id, access_hash=0) elif is_group: peer = InputPeerChat(chat_id=chat_id) else: peer = InputPeerUser(user_id=chat_id, access_hash=0) return peer, msg_id
async def my_event_handler(event): await client.get_entity('Shit') current_sentence = event.raw_text #print(okt.pos(current_sentence)) print(event.message.to_id.chat_id) print(event) if event.message.to_id.chat_id == 340126983: for n in banned_word: if n in current_sentence: splitted = jamo_split(current_sentence) ##error_sentence = "dont say"+ splitted +" please" error_sentence = splitted merged_sentence = jamo_combine(error_sentence) await client.send_message( InputPeerUser(event.message.from_id, contact_list[event.message.from_id]), error_sentence) await client.send_message( InputPeerUser(event.message.from_id, contact_list[event.message.from_id]), merged_sentence)
def send_message(msg): client = TelegramClient('session', api_id, api_hash) client.connect() if not client.is_user_authorized(): client.send_code_request(phone) client.sign_in(phone, input('Enter the code: ')) try: receiver = InputPeerUser('user_id', 'user_hash') client.send_message(receiver, msg, parse_mode='html') except Exception as e: print(e) client.disconnect()
def messasge_send(client, user_id, user_hash): try: receiver = InputPeerUser(user_id, user_hash) # sending message using telegram client client.send_message(receiver, "Hello", parse_mode='html') except Exception as e: # there may be many error coming in while like peer # error, wwrong access_hash, flood_error, etc print(e)
def send_text_message(self, to, body, first_name, last_name=None): contactModel = self.get_or_create_new_contact(to, first_name, last_name=last_name) if contactModel is None: return None peer_user = InputPeerUser(int(contactModel.user_id), int(contactModel.access_hash)) msg_id = self.send_message(peer_user, body, no_web_page=True) logging.info('Send message id {}'.format(msg_id)) return msg_id
async def main(): chat =await client.get_input_entity('Shit') print("Received Data!!") async for messages in client.iter_messages(chat): current_sentence=messages.message if current_sentence == None: break print(messages.from_id," : ",current_sentence) if current_sentence.find(banned_word) ==0 : print(current_sentence.find(banned_word)) print("he said ",banned_word) await client.send_message(InputPeerUser(messages.from_id, contact_list[messages.from_id]), error_sentence)
async def send_msg(self, client, minute): # get_entity = await client.get_entity(last_name + first_name) get_entity = await client.get_entity(nick_name) async for user in client.iter_participants(get_entity): print(user.id) receiver = InputPeerUser(get_entity.id, get_entity.access_hash) # sending message using telegram client await client.send_message(receiver, str(minute) + "분 이 초과됬습니다.", parse_mode='html')
def msg_all(): input_file = "ext_members.csv" users = [] with open(input_file, encoding='UTF-8') as f: rows = csv.reader(f, delimiter=",", lineterminator="\n") next(rows, None) for row in rows: user = {} user['username'] = row[0] user['id'] = int(row[1]) user['access_hash'] = int(row[2]) user['name'] = row[3] users.append(user) mode = int(input("Enter 1 to send by user ID or 2 to send by username: "******"Hello {}, How are you?", "Hi {}, What's up?", "Hey {}, do you want to gotrained?" ] for user in users: if mode == 2: if user['username'] == "": continue receiver = client.get_input_entity(user['username']) elif mode == 1: receiver = InputPeerUser(user['id'], user['access_hash']) else: print("Invalid Mode. Exiting.") client.disconnect() sys.exit() message = random.choice(messages) try: print("Sending Message to:", user['name']) client.send_message(receiver, message.format(user['name'])) print("Waiting {} seconds".format(SLEEP_TIME)) time.sleep(SLEEP_TIME) except PeerFloodError: print( "Getting Flood Error from telegram. Script is stopping now. Please try again after some time." ) client.disconnect() sys.exit() except Exception as e: print("Error:", e) print("Trying to continue...") continue client.disconnect() print("Done. Message sent to all users.")
def do_status_read(self, to, max_id): contactModel = None try: contactModel = TLContact.objects.get(owner=self.user_phone, phone=to) except ObjectDoesNotExist: logging.error( 'Error do_status_read : User {} does not have contact {}'. format(self.user_phone, to)) return peer_user = InputPeerUser(int(contactModel.user_id), int(contactModel.access_hash)) result = self.send_read_acknowledge(peer_user, max_id=max_id)
async def addUserToMutualContact(client, user, name, secname, phone, id, hash): try: if name == None: name = "" if secname == None: secname = "" await client(AddContactRequest(user, name, secname, "+145055554953")) return InputPeerUser(id, hash) except errors.FloodWaitError as e: print('Flood uyarısı alındı.', e.seconds, ' saniye bekleniyor') return FloodReturn(True, e.seconds) except Exception as e: print("Bilinmeyen hata") print(e) return None
def starting(): global y mode = 2 n = 0 for user in users: n += 1 print(n) if n % 50 == 0: time.sleep(900) try: print("Adding {}".format(user['id'])) if mode == 1: print("mod 1") if user['username'] == "": continue user_to_add = client.get_input_entity(user['username']) elif mode == 2: print("mod 2") # defining user id as a a = user["id"] user_to_add = InputPeerUser(user['id'], user['access_hash']) else: print("mod 3'") sys.exit("Invalid Mode Selected. Please Try Again.") client( InviteToChannelRequest(adding_members_to_save, [user_to_add])) seconds = random.randrange(60, 180) text = "adding " + str(a) + " to " + str( adding_members_to_save.title) + " and waiting " + str( seconds) + " seconds" tkinter_label(text, n) y += 60 time.sleep(seconds) except PeerFloodError: print( "Getting Flood Error from telegram. Script is stopping now. Please try again after some time." ) except UserPrivacyRestrictedError: print( "The user's privacy settings do not allow you to do this. Skipping." ) except: traceback.print_exc() print("Unexpected Error") continue
async def purge_hostiles(hostile_dict): ban_count = ban_attempts = 0 try: for group in settings['groups_to_preserve']: banned_users = [] group = await client.get_input_entity(group) try: with open(f'{banned_path}/{group.channel_id}.json', 'r') as banned_file: banned_users = json.load(banned_file) except FileNotFoundError: pass for h_id, hostile in hostile_dict.items(): # Skip already banned users if h_id in banned_users: continue ban_attempts += 1 user = InputPeerUser(hostile['id'], hostile['access_hash']) try: await client.edit_permissions(group, user, view_messages=False) except BadRequestError as e: logger.error(f"{e} while processing: {hostile} ") continue banned_users.append(hostile['id']) ban_count += 1 logger.info(f'Banned {stringify_user_dict(hostile)}') if ban_attempts % cool_down_limit == 0: logger.info( 'Cooling down in order to avoid flood limit, wait' f' {timedelta(seconds=cool_down_time)}') sleep(cool_down_time) with open(f'{banned_path}/{group.channel_id}.json', 'w') as banned_file: json.dump(banned_users, banned_file) except KeyboardInterrupt: pass finally: return ban_count
def send_smss(self, input_file): users = [] with open(input_file, encoding='UTF-8') as f: rows = csv.reader(f, delimiter=",", lineterminator="\n") next(rows, None) for row in rows: user = {} user['username'] = row[0] user['id'] = int(row[1]) user['access_hash'] = int(row[2]) user['name'] = row[3] users.append(user) print("[1] send sms by user ID\n[2] send sms by username ") mode = int(input("Input : ")) message = input("[+] Enter Your Message : ") auth_srv = auth_service.AuthService() client = auth_srv.auth() for user in users: if mode == 2: if user['username'] == "": continue receiver = client.get_input_entity(user['username']) elif mode == 1: receiver = InputPeerUser(user['id'], user['access_hash']) else: print("[!] Invalid Mode. Exiting.") client.disconnect() sys.exit() try: print("[+] Sending Message to:", user['name']) client.send_message(receiver, message.format(user['name'])) print("[+] Waiting {} seconds".format(SLEEP_TIME)) time.sleep(SLEEP_TIME) except PeerFloodError: print( "[!] Getting Flood Error from telegram. \n[!] Script is stopping now. \n[!] Please try again " "after some time.") client.disconnect() sys.exit() except Exception as e: print("[!] Error:", e) print("[!] Trying to continue...") continue client.disconnect() print("Done. Message sent to all users.")
def print_dialogs(self, history_limit=15): """ returns a dictionary{user: messages} listing all the messages from a specified user set (created at __init__) :return: dict """ message_dict = {} with self._client: dialogs = self._client.loop.run_until_complete( self.get_dialogs()) # gets the chats users = {u.id: u for u in dialogs.users} for dialog in dialogs.dialogs: peer = dialog.peer # analyzes only chats with users and not groups or channels if isinstance(peer, PeerUser): id = peer.user_id user = users[id] access_hash = user.access_hash username = user.username name = "{0} {1}".format( str(user.first_name), str(user.last_name) if user.last_name is not None else '') if self._user_set is not None: # if user set not specified, analyzes all the chats # else it skips the ones that are not in user set if username not in self._user_set: continue input_peer = InputPeerUser(id, access_hash) get_history = GetHistoryRequest(peer=input_peer, offset_id=0, offset_date=None, add_offset=0, limit=history_limit, max_id=0, min_id=0, hash=0) with self._client: history = self._client.loop.run_until_complete( self.get_history(get_history)) messages = history.messages message_dict[name] = messages if message_dict: return message_dict else: raise NoMessagesFound
async def send_msg(room_id, message, from_group=None): """ Sends the message to the particular chat """ async with start_bot_client() as bot: current_bot = await bot.get_me() chat_object = get_chat_by_telegram_id(room_id) # dynamically set from_group or ensure explicit param correctly identified the chat type computed_from_group = isinstance(chat_object, GroupChat) if from_group is None: from_group = computed_from_group elif from_group != computed_from_group: raise Exception('Unexpected chat type / group flag combination') if from_group: receiver = await bot.get_entity(PeerChat(room_id)) else: access_hash = chat_object.access_hash receiver = InputPeerUser(room_id, int(access_hash)) msg_inst = await bot.send_message(receiver, message) message_data = { ROOM_ID: room_id, MESSAGE: message, FROM_GROUP: from_group, SENDER_ID: current_bot.id, SENDER_NAME: current_bot.first_name, TELEGRAM_MSG_ID: msg_inst.id } serializer = MessageSerializer(data=message_data) if serializer.is_valid(): serializer.save() await handle_post_message_send_actions(chat_object, serializer.data) return { DATA: { MESSAGE: serializer.data, IS_SUCCESS: True }, STATUS: status.HTTP_200_OK, }
async def add(self, target_group, members, from_group): self._run = True target_group_entity = InputPeerChannel(target_group.id, target_group.access_hash) # print(from_group) # print(type(from_group)) # await self.client(ImportChatInviteRequest(from_group.access_hash)) # print("Joined Channel") # await self.list_groups() x = 0 phone_data = json.load(open(build_phone_path(self.phone))) while (self._run and x < len(members)): try: delay = TGClient.DELAY user = members[x] user_to_add = InputPeerUser(user['id'], user['access_hash']) message = "Adding {name} to Group".format(name=user["name"]) await self.client( InviteToChannelRequest(target_group_entity, [user_to_add])) except PeerFloodError: delay = delay * 5 message = "Getting Flood Error from telegram. Waiting {delay} seconds".format( delay=delay) except UserPrivacyRestrictedError: message = "The user's privacy settings do not allow you to do this. Skipping." delay = 0.5 except Exception as e: message = str(e) delay = 0.5 print("USER: "******"name"]) print("USER ID: ", user["id"]) update_config = dict(message=message, count=x + 1, timestamp=datetime.now().timestamp() + delay) phone_data.update(update_config) save_phone(phone_data, self.phone) x += 1 await asyncio.sleep(delay) if self._run: phone_data.update({"message": "All users in list processed"}) save_phone(phone_data, self.phone)