async def main(): for user in USER_LIST: title = f'{config["title"]["group"]} {user}' result = await client(CreateChatRequest(users=[user], title=title)) group_id = result.chats[0].id print(f'telegram group "{title}" created!') main_user = await client(GetFullUserRequest(user)) user_id = main_user.user.id user_username = main_user.user.username await client.edit_admin(-group_id, user_id, is_admin=True, add_admins=False) print(f"{user} is an Admin now!") add_invite_link = await client(ExportChatInviteRequest(group_id)) invite_link = add_invite_link.link with open(OUTPUT_FILE_NAME, "a", encoding="utf-8") as output_file: information = ( f"user: {user_username} \t group_name: {title} \t invite_link: {invite_link}\n" ) output_file.write(information) print(f"RECORDED {OUTPUT_FILE_NAME}: {information}")
async def run(creation_q, cfg): global config config = cfg client = await TelegramClient('anon', config["api_id"], config["api_hash"]).start() while True: if not creation_q.empty(): group = creation_q.get() exists = False async for dialog in client.iter_dialogs(): if dialog.title == group: exists = True logger.debug( 'Group chat "{}" already exists'.format(group)) if not exists: chat = await client( CreateChatRequest(users=[config["bot_username"]], title=group)) logger.debug('Created new group chat "{}"'.format(group)) creation_q.task_done() await asyncio.sleep(0.5)
async def create_group(manager, event): # creating group with our bot added and getting invite link for it try: update = await manager( CreateChatRequest(title=f'Shop chat ID {event.message.text[7:]}', users=[config.bot_name])) new_group = update.updates[2].message.to_id update = await manager(ExportChatInviteRequest(new_group)) except RPCError as err: await error("Group creation failed", err) return else: await event.message.reply(update.link) # group created, sending id to app try: conducte_requests.send_group(new_group.chat_id, update.link) except RequestException as err: await error("App request failed", err) await manager.kick_participant(new_group, 'me') else: # adding event handler for when first user has joined client.add_event_handler( promote_admin, events.ChatAction(chats=new_group.chat_id, func=lambda event: event.user_joined)) logger.info("Group created, id: %s", new_group.chat_id)
async def create_super_group(client, username, group_title): print('Creating new super group.') r = CreateChatRequest(users=[username], title=group_title) result = await client(r) await asyncio.sleep(1) group_id = result.updates[-1].peer.chat_id r = MigrateChatRequest(group_id) result = await client(r) await asyncio.sleep(1) return result.updates[0].channel_id
async def create_telegram_chat(self, source: 'u.User', invites: List[InputUser], supergroup: bool = False) -> None: if not self.mxid: raise ValueError( "Can't create Telegram chat for portal without Matrix room.") elif self.tgid: raise ValueError( "Can't create Telegram chat for portal with existing Telegram chat." ) if len(invites) < 2: if self.bot is not None: info, mxid = await self.bot.get_me() raise ValueError( "Not enough Telegram users to create a chat. " "Invite more Telegram ghost users to the room, such as the " f"relaybot ([{info.first_name}](https://matrix.to/#/{mxid}))." ) raise ValueError("Not enough Telegram users to create a chat. " "Invite more Telegram ghost users to the room.") if self.peer_type == "chat": response = await source.client( CreateChatRequest(title=self.title, users=invites)) entity = response.chats[0] elif self.peer_type == "channel": response = await source.client( CreateChannelRequest(title=self.title, about=self.about or "", megagroup=supergroup)) entity = response.chats[0] await source.client( InviteToChannelRequest(channel=await source.client.get_input_entity(entity), users=invites)) else: raise ValueError("Invalid peer type for Telegram chat creation") self.tgid = entity.id self.tg_receiver = self.tgid self.by_tgid[self.tgid_full] = self await self.update_info(source, entity) self.db_instance.insert() self.log = self.base_log.getChild(self.tgid_log) if self.bot and self.bot.tgid in invites: self.bot.add_chat(self.tgid, self.peer_type) levels = await self.main_intent.get_power_levels(self.mxid) if levels.get_user_level(self.main_intent.mxid) == 100: levels = self._get_base_power_levels(levels, entity) await self.main_intent.set_power_levels(self.mxid, levels) await self.handle_matrix_power_levels(source, levels.users, {}, None) await self.update_bridge_info()
def create_group(uids, group_name): """ create telegram group for given users list """ users = list(map(get_input_user, uids)) group = CreateChatRequest(users, group_name) try: result = client.invoke(group) return result, False except Exception as e: return e, True
async def _(e): type_of_group = e.pattern_match.group(1) group_name = e.pattern_match.group(2) username = None if " ; " in group_name: group_ = group_name.split(" ; ", maxsplit=1) group_name = group_[0] username = group_[1] xx = await eor(e, get_string("com_1")) if type_of_group == "b": try: r = await e.client( CreateChatRequest( users=["@missrose_bot"], title=group_name, ), ) created_chat_id = r.chats[0].id await e.client( DeleteChatUserRequest( chat_id=created_chat_id, user_id="@missrose_bot", ), ) result = await e.client( ExportChatInviteRequest(peer=created_chat_id, ), ) await xx.edit( get_string("chats_4").format(group_name, result.link), link_preview=False, ) except Exception as ex: await xx.edit(str(ex)) elif type_of_group in ["g", "c"]: try: r = await e.client( CreateChannelRequest( title=group_name, about=get_string("chats_5"), megagroup=type_of_group != "c", )) created_chat_id = r.chats[0].id if username: await e.client(UpdateUsernameRequest(created_chat_id, username)) result = "https://t.me/" + username else: result = (await e.client( ExportChatInviteRequest(peer=created_chat_id, ), )).link await xx.edit( get_string("chats_6").format(f"[{group_name}]({result})"), link_preview=False, ) except Exception as ex: await xx.edit(str(ex))
async def _(e): if BOT_MODE: return await eor(e, "You Cant use this Command in BOT_MODE") type_of_group = e.pattern_match.group(1) group_name = e.pattern_match.group(2) xx = await eor(e, "`Processing...`") if type_of_group == "b": try: r = await e.client( CreateChatRequest( users=["@missrose_bot"], title=group_name, ), ) created_chat_id = r.chats[0].id await e.client( DeleteChatUserRequest( chat_id=created_chat_id, user_id="@missrose_bot", ), ) result = await e.client( ExportChatInviteRequest( peer=created_chat_id, ), ) await xx.edit( f"Your [{group_name}]({result.link}) Group Made Boss!", link_preview=False, ) except Exception as ex: await xx.edit(str(ex)) elif type_of_group == "g" or type_of_group == "c": try: r = await e.client( CreateChannelRequest( title=group_name, about="CREATED BY INFINATO", megagroup=False if type_of_group == "c" else True, ), ) created_chat_id = r.chats[0].id result = await e.client( ExportChatInviteRequest( peer=created_chat_id, ), ) await xx.edit( f"Your [{group_name}]({result.link}) Group/Channel Has been made Boss!", link_preview=False, ) except Exception as ex: await xx.edit(str(ex))
async def create_group(phone, code, token, group_name, members): try: client = await TelegramService.get_client(phone) await client.sign_in(phone, code, phone_code_hash=token) if await client.is_user_authorized(): await client(CreateChatRequest(users=members, title=group_name)) return {}, 201 else: return {'message': 'user not authorized'}, 401 except Exception as e: return TelegramService.handle_error(e)
async def _(event): if BOT_MODE: return await eor(event, "`Anda tidak bisa menggunakan perintah ini di BOT_MODE.`") tipe = event.pattern_match.group(1) nama = event.pattern_match.group(2) xx = await eor(event, "`Memprossess...`") if tipe == "g": try: r = await event.client( CreateChatRequest( users=["@missrose_bot"], title=nama, ), ) cht_id = r.chats[0].id await event.client( DeleteChatUserRequest( chat_id=cht_id, user_id="@missrose_bot" ) ) res = await event.client( ExportChatInviteRequest( peer=cht_id ) ) await xx.edit( f"[{nama}]({res.link}) Berhasil dibuat!", link_preview=False ) except Exception as EXcep: await xx.edit(str(EXcep)) elif tipe == "c": try: r = await event.client( CreateChannelRequest( title=nama, about="Join @KingUserbotSupport", megagroup=False ) ) cht_id = r.chats[0].id res = await event.client( ExportChatInviteRequest( peer=cht_id ) ) await xx.edit( f"[{nama}]({res.link}) Berhasil dibuat!", link_preview=False ) except Exception as EXcep: await xx.edit(str(EXcep))
async def _(e): type_of_group = e.pattern_match.group(1) group_name = e.pattern_match.group(2) username = None if " ; " in group_name: group_ = group_name.split(" ; ", maxsplit=1) group_name = group_[0] username = group_[1] xx = await eor(e, "`Processing...`") if type_of_group == "b": try: r = await e.client( CreateChatRequest( users=["@missrose_bot"], title=group_name, ), ) created_chat_id = r.chats[0].id await e.client( DeleteChatUserRequest( chat_id=created_chat_id, user_id="@missrose_bot", ), ) result = await e.client( ExportChatInviteRequest(peer=created_chat_id, ), ) await xx.edit( f"Your [{group_name}]({result.link}) Group Made Boss!", link_preview=False, ) except Exception as ex: await xx.edit(str(ex)) elif type_of_group in ["g", "c"]: try: r = await e.client( CreateChannelRequest( title=group_name, about="Join @TeamUltroid", megagroup=type_of_group != "c", )) created_chat_id = r.chats[0].id if username: await e.client(UpdateUsernameRequest(created_chat_id, username)) result = "https://t.me/" + username else: result = (await e.client( ExportChatInviteRequest(peer=created_chat_id, ), )).link await xx.edit( f"Your [{group_name}]({result}) Group/Channel Has been made Boss!", link_preview=False, ) except Exception as ex: await xx.edit(str(ex))
async def test_group_chat_migration(client, helper, channel, slave, bot_id): slave_chats = slave.chats_by_chat_type["PrivateChat"] response = await client( CreateChatRequest(users=[bot_id], title=f"Chat upgrade test {uuid4()}")) chat: TelethonChat = response.chats[0] with link_chats(channel, slave_chats, get_peer_id(chat)): mega_chat_response = await client(MigrateChatRequest(chat_id=chat.id)) mega_chat: TelethonChat = mega_chat_response.chats[1] await asyncio.sleep(10) assert_is_linked(channel, slave_chats, get_peer_id(mega_chat)) assert_is_linked(channel, tuple(), get_peer_id(chat)) # Clean up unlink_all_chats(channel, get_peer_id(mega_chat)) unlink_all_chats(channel, get_peer_id(chat)) await client(DeleteChannelRequest(mega_chat.id))
async def run(tgsQ, cfg): logger.info("Starting Telethon Self-Bot") try: client = await TelegramClient('anon', int(cfg["api_id"]), cfg["api_hash"]).start() except Exception as e: logger.error("Telethon was unable to start:\n" + str(e)) return while True: if not tgsQ.empty(): todoChat = tgsQ.get() chatMap = utils.get_chatmap() try: chat = await client( CreateChatRequest(users=[cfg["bot_username"]], title=todoChat.title)) except Exception as e: logger.error( "Telethon was unable to create a group with name {}:\n{}". format(todoChat.title, str(e))) continue try: await client( EditChatAdminRequest(int('-' + str(chat.chats[0].id)), cfg["bot_username"], is_admin=True)) except Exception as e: logger.error( "Telethon was unable to give admin permission to the bot. " "Please give the WTT bot admin permission in {}".format( todoChat.title)) logger.info('Created new chat "{}"'.format(todoChat.title)) tgID = '-' + str(chat.chats[0].id) chatMap[tgID] = {"waID": todoChat.waID, "title": todoChat.title} utils.save_chatmap(chatMap) tgsQ.task_done() await asyncio.sleep(0.5)
def find_birthdays(client, token): url = "https://birthday.knazarov.com/birthdays?token=%s" % token req = requests.get(url) req.raise_for_status() res = req.json() for birthday in res: person = birthday["name"] date = birthday["date"] invitees = birthday["invitees"] dialog = find_birthday_chat(client, person) if dialog is not None: print("Birthday chat already exists for %s" % person) else: print("Creating birthday chat for %s" % person) client(CreateChatRequest(invitees, '%s birthday: %s' % (person, date)))
def create_birthday_chat(client, config, birthday_guy, responsible_guy, employees): congratulators_usernames = [] for employee in employees: if employee.username != birthday_guy.username: congratulators_usernames.append(employee.username) updates = client( CreateChatRequest(users=congratulators_usernames, title=config["TITLE_TEMPLATE"].format( name=birthday_guy.name, day=birthday_guy.birthday.day, month=birthday_guy.birthday.month, year=birthday_guy.birthday.year))) birthday_chat = updates.chats[0] # Setting responsible_guy as admin client(ToggleChatAdminsRequest(chat_id=birthday_chat.id, enabled=True)) client( EditChatAdminRequest(chat_id=birthday_chat.id, user_id=responsible_guy.username, is_admin=1)) # Sending greeting message client.send_message( birthday_chat, config["GREETING_MESSAGE"].format( name=birthday_guy.name, responsible_guy_name=responsible_guy.name, responsible_guy_username=responsible_guy.username)) # Deleting myself in case its my birthday if birthday_guy.username == config["MyUsername"]: client( DeleteChatUserRequest(chat_id=birthday_chat.id, user_id=config["MyUsername"])) return 0