async def _(event): user = event.sender chat = event.chat_id if event.is_group: fed_id = sql.get_fed_id(chat) if not fed_id: return await event.reply("This chat isn't in any federations.") else: fedowner = sql.get_user_owner_fed_full(event.sender_id) if not fedowner: return await event.reply( "It doesn't look like you have a federation yet!") for f in fedowner: fed_id = "{}".format(f["fed_id"]) info = sql.get_fed_info(fed_id) name = info["fname"] if is_user_fed_admin(fed_id, user.id) is False: return await event.reply(f"You aren't a federation admin for {name}!") input = event.pattern_match.group(1) if input: arg = input.split(" ", 1) if not event.reply_to_msg_id: if len(arg) == 2: iid = arg[0] reason = arg[1] else: iid = arg[0] reason = None if not iid.isnumeric(): entity = await tbot.get_input_entity(iid) try: r_sender_id = entity.user_id except Exception: await event.reply("Couldn't fetch that user.") return else: r_sender_id = int(iid) try: replied_user = await tbot(GetFullUserRequest(r_sender_id)) fname = replied_user.user.first_name username = replied_user.user.username lname = replied_user.user.last_name except Exception: fname = "User" username = None lname = None else: reply_message = await event.get_reply_message() iid = reply_message.sender_id fname = reply_message.sender.first_name lname = reply_message.sender.last_name username = reply_message.sender.username if input: reason = input else: reason = None r_sender_id = iid if r_sender_id == BOT_ID or r_sender_id == OWNER_ID: return await event.reply( "Oh you're a funny one aren't you! I am _not_ going to fedban myself." ) name = info["fname"] if is_user_fed_owner(fed_id, int(r_sender_id)) is True: return await event.reply( f"I'm not banning a fed admin from their own fed! [{name}]") if is_user_fed_admin(fed_id, int(r_sender_id)) is True: return await event.reply( f"I'm not banning a fed admin from their own fed! [{name}]") fban_user_id = int(r_sender_id) fban_user_name = fname fban_user_lname = lname fban_user_uname = username fban, fbanreason, fbantime = sql.get_fban_user(fed_id, int(r_sender_id)) if fban: if fbanreason == '' and reason == None: return await event.reply( f'User [{fname}](tg://)/user?id={r_sender_id}) is already banned in {name}. There is no reason set for their fedban yet, so feel free to set one.' ) if reason == fbanreason: return await event.reply( f'User [{fname}](tg://user?id={r_sender_id}) has already been fbanned, with the exact same reason.' ) if reason == None: if fbanreason == '': return await event.reply( f'User [{fname}](tg://user?id={r_sender_id}) is already banned in {name}.' ) else: return await event.reply( f'User [{fname}](tg://user?id={r_sender_id}) is already banned in {name}, with reason:\n`{fbanreason}`.' ) if not fban: current_datetime = datetime.now(pytz.timezone("Asia/Kolkata")) kuk = f"{current_datetime}" mal = kuk[:10] rec = mal.replace("-", "") x = sql.fban_user( fed_id, fban_user_id, fban_user_name, fban_user_lname, fban_user_uname, reason, int(rec), ) sax = "**New FedBan**\n" sax += f"**Fed:** {name}\n" sax += f"**FedAdmin:** [{event.sender.first_name}](tg://user?id={event.sender_id})\n" sax += f"**User:** [{fname}](tg://user?id={r_sender_id})\n" sax += f"**User ID:** `{r_sender_id}`\n" sax += f"**Reason:** {reason}" else: current_datetime = datetime.now(pytz.timezone("Asia/Kolkata")) kuk = f"{current_datetime}" mal = kuk[:10] rec = mal.replace("-", "") fed_name = info["fname"] temp = sql.un_fban_user(fed_id, fban_user_id) if not temp: await event.reply("Failed to update the reason for fedban!") return x = sql.fban_user( fed_id, fban_user_id, fban_user_name, fban_user_lname, fban_user_uname, reason, int(rec), ) sax = "**FedBan Reason Update**\n" sax += f"**Fed:** {name}\n" sax += f"**FedAdmin:** [{event.sender.first_name}](tg://user?id={event.sender_id})\n" sax += f"**User:** [{fname}](tg://user?id={r_sender_id})\n" sax += f"**User ID:** `{r_sender_id}`\n" if not fbanreason == '': sax += f"**Previous Reason:** {fbanreason}\n" sax += f"**New Reason:** {reason}" await tbot.send_message(event.chat_id, sax) getfednotif = sql.user_feds_report(info["owner"]) if getfednotif: if int(info["owner"]) != int(chat): await tbot.send_message(int(info["owner"]), sax) get_fedlog = sql.get_fed_log(fed_id) if get_fedlog: if int(get_fedlog) != int(chat): await tbot.send_message(int(get_fedlog), sax) fed_chats = list(sql.all_fed_chats(fed_id)) if len(fed_chats) != 0: for fedschat in fed_chats: try: await tbot( EditBannedRequest(int(fedschat), int(fban_user_id), BANNED_RIGHTS)) except Exception: pass subscriber = list(sql.get_subscriber(fed_id)) if len(subscriber) != 0: for fedsid in subscriber: all_fedschat = sql.all_fed_chats(fedsid) for fedschat in all_fedschat: try: await tbot( EditBannedRequest(int(fedschat), int(fban_user_id), BANNED_RIGHTS)) except Exception: continue
async def endgmute(event): if any([ x in event.raw_text for x in ( "/ungmute", "!ungmute", "aungmute", "bungmute", "cungmute", "dungmute", "eungmute", "fungmute", "gungmute", "hungmute", "iungmute", "jungmute", "kungmute", "lungmute", "mungmute", "nungmute", "oungmute", "pungmute", "qungmute", "rungmute", "sungmute", "tungmute", "uungmute", "vungmute", "wungmute", "xungmute", "yungmute", "zungmute", "1ungmute", "2ungmute", "3ungmute", "4ungmute", "5ungmute", "6ungmute", "7ungmute", "8ungmute", "9ungmute", "0ungmute", "Aungmute", "Bungmute", "Cungmute", "Dungmute", "Eungmute", "Fungmute", "Gungmute", "Hungmute", "Iungmute", "Jungmute", "Kungmute", "Lungmute", "Mungmute", "Nungmute", "Oungmute", "Pungmute", "Qungmute", "Rungmute", "Sungmute", "Tungmute", "Uungmute", "Vungmute", "Wungmute", "Xungmute", "Yungmute", "Zungmute", ) ]): return private = False if event.fwd_from: return elif event.is_private: await event.edit("Unexpected issues or ugly errors may occur!") await asyncio.sleep(3) private = True reply = await event.get_reply_message() if event.pattern_match.group(1) is not None: userid = event.pattern_match.group(1) elif reply is not None: userid = reply.sender_id elif private is True: userid = event.chat_id else: return await event.edit( "Please reply to a user or add their into the command to ungmute them." ) chat_id = event.chat_id replied_user = await event.client(GetFullUserRequest(userid)) if not is_muted(userid, "gmute"): return await event.edit("This user is not gmuted") try: unmute(userid, "gmute") except Exception as e: await event.edit("Error occured!\nError is " + str(e)) else: await event.edit("Successfully ungmuted that person") if BOTLOG: await event.client.send_message( BOTLOG_CHATID, "#UNGMUTE\n" f"USER: [{replied_user.user.first_name}](tg://user?id={userid})\n" f"CHAT: {event.chat.title}(`{event.chat_id}`)")
def import_message(self, client, message, entity, get_full_userinfo=False): """ Convert Message object to 4CAT-ready data object :param TelegramClient client: Telethon TelegramClient instance :param Message message: Message to parse :param bool get_full_userinfo: Whether to get user info for users. Takes an extra request, so it's slow. :return dict: 4CAT-compatible item object """ thread = message.to_id # determine thread ID (= entity ID) if type(thread) == PeerChannel: thread_id = thread.channel_id elif type(thread) == PeerChat: thread_id = thread.chat_id elif type(thread) == PeerUser: thread_id = thread.user_id else: thread_id = 0 # determine username # API responses only include the user *ID*, not the username, and to # complicate things further not everyone is a user and not everyone # has a username. If no username is available, try the first and # last name someone has supplied if message.from_id and not get_full_userinfo: user_id = message.from_id username = None user_is_bot = None elif message.from_id: # this is broken if message.from_id not in self.usermap: user = User(message.from_id) full = client.loop.run_until_complete(GetFullUserRequest(message.from_id)) if full.user.username: self.usermap[message.from_id] = full.user.username elif full.user.first_name: self.usermap[message.from_id] = full.user.first_name if full.user.last_name: self.usermap[message.from_id] += " " + full.user.last_name else: self.usermap[message.from_id] = None self.botmap[message.from_id] = full.user.bot user_id = message.from_id username = self.usermap[message.from_id] user_is_bot = self.botmap[message.from_id] elif message.post_author: user_id = message.post_author username = message.post_author user_is_bot = False else: user_id = "stream" username = None user_is_bot = False # determine media type # these store some extra information of the attachment in # attachment_data. Since the final result will be serialised as a csv # file, we can only store text content. As such some media data is # serialised as JSON. attachment_type = self.get_media_type(message.media) if attachment_type == "contact": attachment = message.contact attachment_data = json.dumps({property: attachment[property] for property in ("phone_number", "first_name", "last_name", "vcard", "user_id")}) elif attachment_type == "document": # videos, etc # This could add a separate routine for videos to make them a # separate type, which could then be scraped later, etc attachment_type = message.media.document.mime_type.split("/")[0] attachment_data = "" elif attachment_type == "game": # there is far more data in the API response for games but this # seems like a reasonable number of items to include attachment = message.game attachment_data = json.dumps( {property: attachment[property] for property in ("id", "short_name", "title", "description")}) elif attachment_type in ("geo", "geo_live"): # untested whether geo_live is significantly different from geo attachment_data = "%s %s" % (message.geo.lat, message.geo.long) elif attachment_type == "invoice": # unclear when and where this would be used attachment = message.invoice attachment_data = json.dumps( {property: attachment[property] for property in ("title", "description", "currency", "total_amount")}) elif attachment_type == "photo": # we don't actually store any metadata about the photo, since very # little of the metadata attached is of interest. Instead, the # actual photos may be downloaded via a processor that is run on the # search results attachment_data = "" elif attachment_type == "poll": # unfortunately poll results are only available when someone has # actually voted on the poll - that will usually not be the case, # so we store -1 as the vote count attachment = message.poll options = {option.option: option.text for option in attachment.poll.answers} attachment_data = json.dumps({ "question": attachment.poll.question, "voters": attachment.results.total_voters, "answers": [{ "answer": options[answer.option], "votes": answer.voters } for answer in attachment.results.results] if attachment.results.results else [{ "answer": options[option], "votes": -1 } for option in options] }) elif attachment_type == "venue": # weird attachment = message.venue attachment_data = json.dumps({**{"geo": "%s %s" % (attachment.geo.lat, attachment.geo.long)}, **{ {property: attachment[property] for property in ("title", "address", "provider", "venue_id", "venue_type")} }}) elif attachment_type == "url": # easy! if hasattr(message.web_preview, "url"): attachment_data = message.web_preview.url else: attachment_data = "" else: attachment_data = "" # was the message forwarded from somewhere and if so when? forwarded = None forwarded_timestamp = None if message.fwd_from: forwarded_timestamp = message.fwd_from.date.timestamp() if message.fwd_from.post_author: forwarded = message.fwd_from.post_author elif message.fwd_from.from_id: forwarded = message.fwd_from.from_id elif message.fwd_from.channel_id: forwarded = message.fwd_from.channel_id else: from_id = "stream" msg = { "id": message.id, "thread_id": thread_id, "search_entity": entity, "author": user_id, "author_name": username, "author_is_bot": user_is_bot, "author_forwarded_from": forwarded, "subject": "", "body": message.message, "reply_to": message.reply_to_msg_id, "views": message.views, "timestamp": int(message.date.timestamp()), "timestamp_edited": int(message.edit_date.timestamp()) if message.edit_date else None, "timestamp_forwarded_from": forwarded_timestamp, "grouped_id": message.grouped_id, "attachment_type": attachment_type, "attachment_data": attachment_data } if not get_full_userinfo: del msg["author_name"] del msg["author_is_bot"] return msg
async def get_curr_track(lfmbio): global ARTIST global SONG global LASTFMCHECK global RUNNING global USER_ID oldartist = "" oldsong = "" while LASTFMCHECK: try: if USER_ID == 0: USER_ID = (await lfmbio.client.get_me()).id user_info = await bot(GetFullUserRequest(USER_ID)) RUNNING = True playing = User(LASTFM_USERNAME, lastfm).get_now_playing() SONG = playing.get_title() ARTIST = playing.get_artist() oldsong = environ.get("oldsong", None) oldartist = environ.get("oldartist", None) if playing is not None and SONG != oldsong and ARTIST != oldartist: environ["oldsong"] = str(SONG) environ["oldartist"] = str(ARTIST) if BIOPREFIX: lfmbio = f"{BIOPREFIX} 🎧: {ARTIST} - {SONG}" else: lfmbio = f"🎧: {ARTIST} - {SONG}" try: if BOTLOG and LastLog: await bot.send_message( BOTLOG_CHATID, f"Biyografi şuna çevrildi: \n{lfmbio}") await bot(UpdateProfileRequest(about=lfmbio)) except AboutTooLongError: short_bio = f"🎧: {SONG}" await bot(UpdateProfileRequest(about=short_bio)) else: if playing is None and user_info.about != DEFAULT_BIO: await sleep(6) await bot(UpdateProfileRequest(about=DEFAULT_BIO)) if BOTLOG and LastLog: await bot.send_message( BOTLOG_CHATID, f"Biyografi geri şuna çevrildi: \n{DEFAULT_BIO}") except AttributeError: try: if user_info.about != DEFAULT_BIO: await sleep(6) await bot(UpdateProfileRequest(about=DEFAULT_BIO)) if BOTLOG and LastLog: await bot.send_message( BOTLOG_CHATID, f"Biyografi geri şuna çevrildi \n{DEFAULT_BIO}") except FloodWaitError as err: if BOTLOG and LastLog: await bot.send_message( BOTLOG_CHATID, f"Biyografi değiştirilirken hata oluştu :\n{err}") except FloodWaitError as err: if BOTLOG and LastLog: await bot.send_message( BOTLOG_CHATID, f"Biyografi değiştirilirken hata oluştu :\n{err}") except WSError as err: if BOTLOG and LastLog: await bot.send_message( BOTLOG_CHATID, f"Biyografi değiştirilirken hata oluştu: \n{err}") await sleep(2) RUNNING = False
async def addcmd(event): user = await bot(GetFullUserRequest(event.sender_id)) async with bot.conversation(user.user.id) as conv: await event.respond( f'Отлично! Теперь пришли мне ссылку на товар.\n__Без корявого перевода плез, я не умею это убирать.__' ) response = conv.wait_event( events.NewMessage(incoming=True, from_users=user.user.id)) response = await response link = f"[{response.text}]({response.text})" await event.respond( 'А теперь придумай мне название для этого говна сука.') response = conv.wait_event( events.NewMessage(incoming=True, from_users=user.user.id)) response = await response name = response.text await event.respond('Заебись! Кто производитель этого говна ебаного?') response = conv.wait_event( events.NewMessage(incoming=True, from_users=user.user.id)) response = await response vendor = ('#' + response.text).replace(' ', '_') click_button1 = KeyboardButtonCallback("Мобильные телефоны", data=b'telephone') click_button2 = KeyboardButtonCallback("Бытовая электроника", data=b'byt_electr') click_button3 = KeyboardButtonCallback("Бытовая техника", data=b'byt_tehn') click_button4 = KeyboardButtonCallback("Безопасность и защита", data=b'bezopas') click_button5 = KeyboardButtonCallback("Компьютер и офис", data=b'computer') click_button6 = KeyboardButtonCallback("Багаж и сумки", data=b'bagazh') click_button7 = KeyboardButtonCallback("Спорт", data=b'sport') click_button8 = KeyboardButtonCallback("Развлечения", data=b'razvle4en') click_button9 = KeyboardButtonCallback("Красота и здоровье", data=b'krasota') click_button10 = KeyboardButtonCallback("Маски", data=b'maski') click_button11 = KeyboardButtonCallback("Одежда", data=b'odezhda') click_button12 = KeyboardButtonCallback("Другое", data=b'other') line1 = KeyboardButtonRow(buttons=[click_button1, click_button2]) line2 = KeyboardButtonRow(buttons=[click_button3, click_button4]) line3 = KeyboardButtonRow(buttons=[click_button5, click_button6]) line4 = KeyboardButtonRow(buttons=[click_button7, click_button8]) line5 = KeyboardButtonRow(buttons=[click_button9, click_button10]) line6 = KeyboardButtonRow(buttons=[click_button11, click_button12]) btns = ReplyInlineMarkup( rows=[line1, line2, line3, line4, line5, line6]) await bot.send_message( event.chat.id, 'Ахуенчик! Теперь выбери категорию, в которой находится товар.', buttons=btns) response = conv.wait_event(events.CallbackQuery) response = await response data = response.data.decode('utf-8') if data == 'telephone': category = '#Мобильные_телефоны' try: ppl = user.user.first_name await publish(name, vendor, category, link, ppl) except Exception: await response.answer(message='Fail') return await event.respond( 'Неудачно высрал на канал бля программист хуесос ебливый нахуй' ) await response.answer(message='OK') return await event.respond('Удачно высрал на канал ебать.') elif data == 'byt_electr': category = '#Бытовая_электроника' try: ppl = user.user.first_name await publish(name, vendor, category, link, ppl) except Exception: await response.answer(message='Fail') return await event.respond( 'Неудачно высрал на канал бля программист хуесос ебливый нахуй' ) await response.answer(message='OK') return await event.respond('Удачно высрал на канал ебать.') elif data == 'byt_tehn': category = '#Бытовая_техника' try: ppl = user.user.first_name await publish(name, vendor, category, link, ppl) except Exception: await response.answer(message='Fail') return await event.respond( 'Неудачно высрал на канал бля программист хуесос ебливый нахуй' ) await response.answer(message='OK') return await event.respond('Удачно высрал на канал ебать.') elif data == 'bezopas': category = '#Безопасность_и_защита' try: ppl = user.user.first_name await publish(name, vendor, category, link, ppl) except Exception: await response.answer(message='Fail') return await event.respond( 'Неудачно высрал на канал бля программист хуесос ебливый нахуй' ) await response.answer(message='OK') return await event.respond('Удачно высрал на канал ебать.') elif data == 'computer': category = '#Компьютер_и_офис' try: ppl = user.user.first_name await publish(name, vendor, category, link, ppl) except Exception: await response.answer(message='Fail') return await event.respond( 'Неудачно высрал на канал бля программист хуесос ебливый нахуй' ) await response.answer(message='OK') return await event.respond('Удачно высрал на канал ебать.') elif data == 'bagazh': category = '#Багаж_и_суки' try: ppl = user.user.first_name await publish(name, vendor, category, link, ppl) except Exception: await response.answer(message='Fail') return await event.respond( 'Неудачно высрал на канал бля программист хуесос ебливый нахуй' ) await response.answer(message='OK') return await event.respond('Удачно высрал на канал ебать.') elif data == 'sport': category = '#Спорт' try: ppl = user.user.first_name await publish(name, vendor, category, link, ppl) except Exception: await response.answer(message='Fail') return await event.respond( 'Неудачно высрал на канал бля программист хуесос ебливый нахуй' ) await response.answer(message='OK') return await event.respond('Удачно высрал на канал ебать.') elif data == 'razvle4en': category = '#Развлечения' try: ppl = user.user.first_name await publish(name, vendor, category, link, ppl) except Exception: await response.answer(message='Fail') return await event.respond( 'Неудачно высрал на канал бля программист хуесос ебливый нахуй' ) await response.answer(message='OK') return await event.respond('Удачно высрал на канал ебать.') elif data == 'krasota': category = '#Красота_и_здоровье' try: ppl = user.user.first_name await publish(name, vendor, category, link, ppl) except Exception: await response.answer(message='Fail') return await event.respond( 'Неудачно высрал на канал бля программист хуесос ебливый нахуй' ) await response.answer(message='OK') return await event.respond('Удачно высрал на канал ебать.') elif data == 'maski': category = '#Маски' try: ppl = user.user.first_name await publish(name, vendor, category, link, ppl) except Exception: await response.answer(message='Fail') return await event.respond( 'Неудачно высрал на канал бля программист хуесос ебливый нахуй' ) await response.answer(message='OK') return await event.respond('Удачно высрал на канал ебать.') elif data == 'odezhda': category = '#Одежда' try: ppl = user.user.first_name await publish(name, vendor, category, link, ppl) except Exception: await response.answer(message='Fail') return await event.respond( 'Неудачно высрал на канал бля программист хуесос ебливый нахуй' ) await response.answer(message='OK') return await event.respond('Удачно высрал на канал ебать.') elif data == 'other': category = '#Другое' try: ppl = user.user.first_name await publish(name, vendor, category, link, ppl) except Exception: await response.answer(message='Fail') return await event.respond( 'Неудачно высрал на канал бля программист хуесос ебливый нахуй' ) await response.answer(message='OK') return await event.respond('Удачно высрал на канал ебать.') else: await event.respond('Ебать ты как из палаты выбрался шизоид ебаный' ) return await response.answer( message='Ты как ебать это сделал нахуй')
def get_latest_news(): logging.info('Started get latest news') try: result = [] for the_file in os.listdir(os.path.join(PATH_TO_EXPORT_DATA, 'images')): file_path = os.path.join( os.path.join(PATH_TO_EXPORT_DATA, 'images'), the_file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: print(e) # GET CHANNEL ENTITY channel_entity = client.get_entity(GROUP_NAME) # GET HISTORY m = client( GetHistoryRequest(peer=channel_entity, limit=15, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, hash=0)) logging.info(f'Getting {len(m.messages)}') for message in m.messages: date = message.date local_tz = pytz.timezone('Europe/Minsk') local_dt = date.replace(tzinfo=pytz.utc).astimezone(local_tz) user = client(GetFullUserRequest(id=message.from_id)) user = user.to_dict() photo = client( functions.photos.GetUserPhotosRequest( user_id=user['user']['id'], offset=0, max_id=0, limit=1)) dict_message = message.message.replace("\n", "") if (not len(dict_message)): continue dict_filepath = f'images/{user["user"]["id"]}.jpg' dict_id = message.id dict_name = f'{user["user"].get("first_name")} {user["user"].get("last_name", "")}' dict_date = local_dt.strftime('%Y-%m-%d %H:%I:%S') result.append({ 'id': dict_id, 'name': dict_name, 'message': dict_message, 'date': dict_date, 'image_path': dict_filepath }) client.download_media( photo.photos[0], os.path.join(PATH_TO_EXPORT_DATA, dict_filepath)) result = list(reversed(result)) with open(os.path.join(PATH_TO_EXPORT_DATA, 'latest_tg_messages.json'), 'w') as fm: fm.write(json.dumps(result)) logging.info(f'Written data') except Exception as e: print(e)
async def throwit(context): if len(context.parameter) > 2: await context.edit("出错了呜呜呜 ~ 无效的参数。") return diu_round = False await context.edit("正在生成 扔头像 图片中 . . .") if context.reply_to_msg_id: reply_message = await context.get_reply_message() if reply_message: user_id = reply_message.from_id target_user = await context.client(GetFullUserRequest(user_id)) if len(context.parameter) == 1: diu_round = True else: await context.edit('出错了呜呜呜 ~ 无法获取所回复的用户。') return else: if len(context.parameter) == 1 or len(context.parameter) == 2: user = context.parameter[0] if user.isnumeric(): user = int(user) else: user_object = await context.client.get_me() user = user_object.id if context.message.entities is not None: if isinstance(context.message.entities[0], MessageEntityMentionName): return await context.client(GetFullUserRequest(context.message.entities[0].user_id)) try: user_object = await context.client.get_entity(user) target_user = await context.client(GetFullUserRequest(user_object.id)) except (TypeError, ValueError, OverflowError, StructError) as exception: if str(exception).startswith("Cannot find any entity corresponding to"): await context.edit("出错了呜呜呜 ~ 指定的用户不存在。") return if str(exception).startswith("No user has"): await context.edit("出错了呜呜呜 ~ 指定的道纹不存在。") return if str(exception).startswith("Could not find the input entity for") or isinstance(exception, StructError): await context.edit("出错了呜呜呜 ~ 无法通过此 UserID 找到对应的用户。") return if isinstance(exception, OverflowError): await context.edit("出错了呜呜呜 ~ 指定的 UserID 已超出长度限制,您确定输对了?") return raise exception photo = await context.client.download_profile_photo( target_user.user.id, "plugins/throwit/" + str(target_user.user.id) + ".jpg", download_big=True ) reply_to = context.message.reply_to_msg_id if exists("plugins/throwit/" + str(target_user.user.id) + ".jpg"): if not exists('plugins/throwit/1.png'): r = get('https://raw.githubusercontent.com/xtaodada/PagerMaid_Plugins/master/throwit/1.png') with open("plugins/throwit/1.png", "wb") as code: code.write(r.content) if not exists('plugins/throwit/2.png'): r = get('https://raw.githubusercontent.com/xtaodada/PagerMaid_Plugins/master/throwit/2.png') with open("plugins/throwit/2.png", "wb") as code: code.write(r.content) if not exists('plugins/throwit/3.png'): r = get('https://raw.githubusercontent.com/xtaodada/PagerMaid_Plugins/master/throwit/3.png') with open("plugins/throwit/3.png", "wb") as code: code.write(r.content) # 随机数生成 randint_r = randint(1, 3) # 将头像转为圆形 markImg = Image.open("plugins/throwit/" + str(target_user.user.id) + ".jpg") if randint_r == 1: thumb_width = 136 elif randint_r == 2: thumb_width = 122 elif randint_r == 3: thumb_width = 180 im_square = crop_max_square(markImg).resize((thumb_width, thumb_width), Image.LANCZOS) im_thumb = mask_circle_transparent(im_square, 0) im_thumb.save("plugins/throwit/" + str(target_user.user.id) + ".png") # 将头像复制到模板上 if randint_r == 1: background = Image.open("plugins/throwit/2.png") elif randint_r == 2: background = Image.open("plugins/throwit/1.png") elif randint_r == 3: background = Image.open("plugins/throwit/3.png") foreground = Image.open("plugins/throwit/" + str(target_user.user.id) + ".png") if len(context.parameter) == 2: diu_round = True if diu_round: foreground = foreground.rotate(180) # 对图片进行旋转 if randint_r == 1: background.paste(foreground, (19, 181), foreground) elif randint_r == 2: background.paste(foreground, (368, 16), foreground) elif randint_r == 3: background.paste(foreground, (331, 281), foreground) background.save('plugins/throwit/throwout.webp') target_file = await context.client.upload_file('plugins/throwit/throwout.webp') try: remove("plugins/throwit/" + str(target_user.user.id) + ".jpg") remove("plugins/throwit/" + str(target_user.user.id) + ".png") remove("plugins/throwit/throwout.webp") remove(photo) except: pass else: await context.edit("此用户未设置头像或头像对您不可见。") return if reply_to: try: await context.client.send_file( context.chat_id, target_file, link_preview=False, force_document=False, reply_to=reply_to ) await context.delete() try: remove(photo) except: pass return except TypeError: await context.edit("此用户未设置头像或头像对您不可见。") except ChatSendStickersForbiddenError: await context.edit("此群组无法发送贴纸。") else: try: await context.client.send_file( context.chat_id, target_file, link_preview=False, force_document=False ) await context.delete() try: remove(photo) except: pass return except TypeError: await context.edit("此用户未设置头像或头像对您不可见。") except ChatSendStickersForbiddenError: await context.edit("此群组无法发送贴纸。")
async def get_user(event, send_text=True): msg = event.message.raw_text.split() user = None if event.reply_to_msg_id: msg = await event.get_reply_message() user = mongodb.user_list.find_one({'user_id': msg.from_id}) # Will ask Telegram for help with it. if not user: try: user = await event.client(GetFullUserRequest(int(msg.from_id))) # Add user in database if user: user = await add_user_to_db(user) except Exception as err: logger.error(err) else: if len(msg) > 1: arg_user = msg[1] else: # Wont tagged any user, lets use sender user = mongodb.user_list.find_one({'user_id': event.from_id}) return user input_str = event.pattern_match.group(1) mention_entity = event.message.entities if input_str and input_str.isdigit(): input_str = int(input_str) # Search user in database if '@' in arg_user: # Remove '@' username = arg_user[1:].lower() user = mongodb.user_list.find_one({'username': username}) elif arg_user.isdigit(): # User id arg_user = int(arg_user) user = mongodb.user_list.find_one({'user_id': int(arg_user)}) else: user = mongodb.user_list.find_one({'username': input_str}) # If we didn't find user in database will ask Telegram. if not user: try: user = await add_user_to_db(await tbot(GetFullUserRequest(arg_user))) except (ValueError, TypeError) as err: logger.debug(f"cant update user E2: {err}") # Still didn't find? Lets try get entities try: if mention_entity: if len(mention_entity) > 1: probable_user_mention_entity = mention_entity[1] else: probable_user_mention_entity = mention_entity[0] if not user: if not isinstance(probable_user_mention_entity, MessageEntityMentionName): user_id = await event.client.get_entity(input_str) else: user_id = probable_user_mention_entity.user_id if user_id: userf = await event.client( GetFullUserRequest(int(user_id))) user = mongodb.user_list.find_one( {'user_id': int(userf.user.id)}) if not user and userf: user = await add_user_to_db(userf) except (ValueError, TypeError) as err: logger.debug(f"cant update user E3: {err}") if not user: # Last try before fail try: user = await event.client.get_entity(input_str) if user: user = await add_user_to_db(user) except (ValueError, TypeError) as err: logger.debug(f"cant update user E4: {err}") if not user and send_text is True: await event.reply("I can't find this user in whole Telegram.") if not user: return None return user
async def _(event): ok = await BotzHub(GetFullUserRequest(event.sender_id)) await event.edit(f"Send or Forward me Supported Media and I will upload it to Telegraph! 🙂️\n\n **Supported Media Formates 🤔️,** \n\n❄️ `Images`\n❄️ `Small Videos`\n❄️ `Gifs`\n❄️ `Some Types Of Stickers`\n\nHosted with ❤️ by **@NexaBotsUpdates** .", buttons=[Button.inline("About 🤷♂️️", data="about"), Button.inline("Credits ❤️", data="credits"), Button.inline("Home 🏘️", data="home")])
async def eat(context: NewMessage.Event): assert isinstance(context.message, Message) if len(context.parameter) > 2: await context.edit("出错了呜呜呜 ~ 无效的参数。") return diu_round = False from_user = user_object = context.sender from_user_id = await get_full_id(from_user) if context.reply_to_msg_id: reply_message = await context.get_reply_message() try: user_id = reply_message.sender_id except AttributeError: await context.edit("出错了呜呜呜 ~ 无效的参数。") return if user_id > 0: target_user = await context.client(GetFullUserRequest(user_id)) target_user_id = target_user.user.id else: target_user = await context.client(GetFullChannelRequest(user_id)) target_user_id = target_user.full_chat.id else: user_raw = "" if len(context.parameter) == 1 or len(context.parameter) == 2: user_raw = user = context.parameter[0] if user.isnumeric(): user = int(user) else: user = from_user_id if context.message.entities is not None: if isinstance(context.message.entities[0], MessageEntityMentionName): target_user = await context.client( GetFullUserRequest(context.message.entities[0].user_id)) target_user_id = target_user.user.id elif isinstance(context.message.entities[0], MessageEntityPhone): if user > 0: target_user = await context.client(GetFullUserRequest(user) ) target_user_id = target_user.user.id else: target_user = await context.client( GetFullChannelRequest(user)) target_user_id = target_user.full_chat.id elif isinstance(context.message.entities[0], MessageEntityBotCommand): target_user = await context.client( GetFullUserRequest(user_object.id)) target_user_id = target_user.user.id else: return await context.edit("出错了呜呜呜 ~ 参数错误。") elif user_raw[:1] in [".", "/", "-", "!"]: target_user_id = await get_full_id(from_user) else: try: user_object = await context.client.get_entity(user) target_user_id = await get_full_id(user_object) except (TypeError, ValueError, OverflowError, StructError) as exception: if str(exception).startswith( "Cannot find any entity corresponding to"): await context.edit("出错了呜呜呜 ~ 指定的用户不存在。") return if str(exception).startswith("No user has"): await context.edit("出错了呜呜呜 ~ 指定的道纹不存在。") return if str(exception).startswith( "Could not find the input entity for") or isinstance( exception, StructError): await context.edit("出错了呜呜呜 ~ 无法通过此 UserID 找到对应的用户。") return if isinstance(exception, OverflowError): await context.edit("出错了呜呜呜 ~ 指定的 UserID 已超出长度限制,您确定输对了?") return raise exception photo = await context.client.download_profile_photo( target_user_id, "plugins/eat/" + str(target_user_id) + ".jpg", download_big=True) reply_to = context.message.reply_to_msg_id if exists("plugins/eat/" + str(target_user_id) + ".jpg"): for num in range(1, max_number + 1): print(num) if not exists('plugins/eat/eat' + str(num) + '.png'): re = get(f'{git_source}eat/eat' + str(num) + '.png') with open('plugins/eat/eat' + str(num) + '.png', 'wb') as bg: bg.write(re.content) if not exists('plugins/eat/mask' + str(num) + '.png'): re = get(f'{git_source}eat/mask' + str(num) + '.png') with open('plugins/eat/mask' + str(num) + '.png', 'wb') as ms: ms.write(re.content) number = randint(1, max_number) try: p1 = 0 p2 = 0 if len(context.parameter) == 1: p1 = context.parameter[0] if p1[0] == ".": diu_round = True if len(p1) > 1: try: p2 = int("".join(p1[1:])) except: # 可能也有字母的参数 p2 = "".join(p1[1:]) elif p1[0] == "-": if len(p1) > 1: try: p2 = int("".join(p1[1:])) except: # 可能也有字母的参数 p2 = "".join(p1[1:]) if p2: redis.set("eat.default-config", p2) await context.edit(f"已经设置默认配置为:{p2}") else: redis.delete("eat.default-config") await context.edit(f"已经清空默认配置") return elif p1[0] == "/": await context.edit(f"正在更新远程配置文件") if len(p1) > 1: # 获取参数中的url p2 = "".join(p1[1:]) if p2 == "delete": redis.delete(configFileRemoteUrlKey) await context.edit(f"已清空远程配置文件url") return if p2.startswith("http"): # 下载文件 if downloadFileFromUrl(p2, configFilePath) != 0: await context.edit(f"下载配置文件异常,请确认url是否正确") return else: # 下载成功,加载配置文件 redis.set(configFileRemoteUrlKey, p2) if await loadConfigFile(context, True) != 0: await context.edit( f"加载配置文件异常,请确认从远程下载的配置文件格式是否正确") return else: await context.edit(f"下载并加载配置文件成功") else: # 根据传入模版id更新模版配置,多个用","或者","隔开 # 判断redis是否有保存配置url splitStr = "," if "," in p2: splitStr = "," ids = p2.split(splitStr) if len(ids) > 0: # 下载文件 configFileRemoteUrl = redis.get( configFileRemoteUrlKey) if configFileRemoteUrl: if downloadFileFromUrl( configFileRemoteUrl, configFilePath) != 0: await context.edit( f"下载配置文件异常,请确认url是否正确") return else: # 下载成功,更新对应配置 if await loadConfigFile(context) != 0: await context.edit( f"加载配置文件异常,请确认从远程下载的配置文件格式是否正确" ) return else: await downloadFileByIds( ids, context) else: await context.edit(f"你没有订阅远程配置文件,更新个🔨") else: # 没传url直接更新 if await updateConfig(context) != 0: await context.edit( f"更新配置文件异常,请确认是否订阅远程配置文件,或从远程下载的配置文件格式是否正确") return else: await context.edit(f"从远程更新配置文件成功") return elif p1[0] == "!" or p1[0] == "!": # 加载配置 if exists(configFilePath): if await loadConfigFile(context) != 0: await context.edit(f"加载配置文件异常,请确认从远程下载的配置文件格式是否正确") return txt = "" if len(positions) > 0: noShowList = [] for key in positions: txt = f"{txt},{key}" if len(positions[key]) > 2: noShowList.append(positions[key][2]) for key in noShowList: txt = txt.replace(f",{key}", "") if txt != "": txt = txt[1:] await context.edit(f"目前已有的模版列表如下:\n{txt}") return defaultConfig = redis.get("eat.default-config") if isinstance(p2, str): number = p2 elif isinstance(p2, int) and p2 > 0: number = int(p2) elif not diu_round and ((isinstance(p1, int) and int(p1) > 0) or isinstance(p1, str)): try: number = int(p1) except: number = p1 elif defaultConfig: try: defaultConfig = defaultConfig.decode() number = int(defaultConfig) except: number = str(defaultConfig) # 支持配置默认是倒立的头像 if number.startswith("."): diu_round = True number = number[1:] except: number = randint(1, max_number) # 加载配置 if exists(configFilePath): if await loadConfigFile(context) != 0: await context.edit(f"加载配置文件异常,请确认从远程下载的配置文件格式是否正确") return try: notifyStr = notifyStrArr[str(number)] except: notifyStr = "吃头像" await context.edit(f"正在生成 {notifyStr} 图片中 . . .") markImg = Image.open("plugins/eat/" + str(target_user_id) + ".jpg") try: eatImg = Image.open("plugins/eat/eat" + str(number) + ".png") maskImg = Image.open("plugins/eat/mask" + str(number) + ".png") except: await context.edit(f"图片模版加载出错,请检查并更新配置:{str(number)}") return if diu_round: markImg = markImg.rotate(180) # 对图片进行旋转 try: number = str(number) except: pass result = await eat_it(context, from_user_id, eatImg, maskImg, markImg, number) result.save('plugins/eat/eat.webp') target_file = await context.client.upload_file("plugins/eat/eat.webp") try: remove("plugins/eat/" + str(target_user_id) + ".jpg") remove("plugins/eat/" + str(target_user_id) + ".png") remove("plugins/eat/" + str(from_user_id) + ".jpg") remove("plugins/eat/" + str(from_user_id) + ".png") remove("plugins/eat/eat.webp") remove(photo) except: pass else: await context.edit("此用户未设置头像或头像对您不可见。") return if reply_to: try: await context.client.send_file(context.chat_id, target_file, link_preview=False, force_document=False, reply_to=reply_to) await context.delete() remove("plugins/eat/eat.webp") try: remove(photo) except: pass return except TypeError: await context.edit("此用户未设置头像或头像对您不可见。") except ChatSendStickersForbiddenError: await context.edit("此群组无法发送贴纸。") else: try: await context.client.send_file(context.chat_id, target_file, link_preview=False, force_document=False) await context.delete() remove("plugins/eat/eat.webp") try: remove(photo) except: pass return except TypeError: await context.edit("此用户未设置头像或头像对您不可见。") except ChatSendStickersForbiddenError: await context.edit("此群组无法发送贴纸。")
async def process_group(group_entity): infiltrators = 0 # The user passed a channel dict if isinstance(group_entity, dict): try: group = InputChannel( group_entity['group_id'], group_entity['group_hash'] ) except KeyError: group = await client.get_input_entity(group_entity['url']) else: group = await client.get_input_entity(group_entity) group_full = await client( GetFullChannelRequest(channel=group) ) target_group_dict = { 'last_update': datetime.now(), 'id': group_full.chats[0].id, 'access_hash': group_full.chats[0].access_hash, 'title': filter_emojis(group_full.chats[0].title), 'members': [] } try: with open(f'{data_path}/{target_group_dict["id"]}.json', 'r') as\ target_group_file: target_group_dict['members'] = \ json.load(target_group_file)['members'] except FileNotFoundError: pass participants = await client.get_participants(group, aggressive=True) for part in participants: try: full_part = await client(GetFullUserRequest(part)) if part.id not in settings['user_exceptions'] and not part.bot\ and full_part.about: logger.debug( f'{stringify_user(part)}: {full_part.about}' ) if any(trigger_word in data_field.casefold() if data_field else None for data_field in [ full_part.about, part.first_name, part.last_name, part.username ] for trigger_word in settings['trigger_words']): member = { 'id': part.id, 'access_hash': part.access_hash, 'first_name': filter_emojis(part.first_name), 'last_name': filter_emojis(part.last_name), 'about': full_part.about, 'username': part.username, 'phone': part.phone } for old_member in target_group_dict['members']: if member['id'] == old_member['id']: target_group_dict['members'].remove(old_member) break target_group_dict['members'].append(member) logger.info( 'Found possible infiltrator: ' f'{stringify_user_dict(member)} ' f'\"{member["about"]}\"' ) infiltrators += 1 except KeyboardInterrupt as e: with open( f'{data_path}/{target_group_dict["id"]}.json', 'w') as\ target_group_file: json.dump(target_group_dict, target_group_file, indent=4, default=str, ensure_ascii=False) raise e with open(f'{data_path}/{target_group_dict["id"]}.json', 'w') as\ target_group_file: json.dump(target_group_dict, target_group_file, indent=4, default=str, ensure_ascii=False) return infiltrators
async def get_curr_track(lfmbio): global ARTIST global SONG global LASTFMCHECK global RUNNING global USER_ID oldartist = "" oldsong = "" while LASTFMCHECK: try: if USER_ID == 0: USER_ID = (await lfmbio.client.get_me()).id user_info = await bot(GetFullUserRequest(USER_ID)) RUNNING = True playing = User(LASTFM_USERNAME, lastfm).get_now_playing() SONG = playing.get_title() ARTIST = playing.get_artist() oldsong = environ.get("oldsong", None) oldartist = environ.get("oldartist", None) if playing is not None and SONG != oldsong and ARTIST != oldartist: environ["oldsong"] = str(SONG) environ["oldartist"] = str(ARTIST) if BIOPREFIX: lfmbio = f"{BIOPREFIX} 🎧: {ARTIST} - {SONG}" else: lfmbio = f"🎧: {ARTIST} - {SONG}" try: if BOTLOG and LastLog: await bot.send_message( BOTLOG_CHATID, f"**Attempted to change bio to**\n{lfmbio}" ) await bot(UpdateProfileRequest(about=lfmbio)) except AboutTooLongError: try: SONG = sub(r"\[.*\]", "", SONG) lfmbio = f"🎧: {ARTIST} - {SONG}" if BOTLOG and LastLog: await bot.send_message( BOTLOG_CHATID, f"**Attempted to change bio to**\n{lfmbio}", ) await bot(UpdateProfileRequest(about=lfmbio)) except AboutTooLongError: try: SONG = sub(r"\(.*\)", "", SONG) lfmbio = f"🎧: {ARTIST} - {SONG}" if BOTLOG and LastLog: await bot.send_message( BOTLOG_CHATID, f"**Attempted to change bio to**\n{lfmbio}", ) await bot(UpdateProfileRequest(about=lfmbio)) except AboutTooLongError: short_bio = f"🎧: {SONG}" if BOTLOG and LastLog: await bot.send_message( BOTLOG_CHATID, f"**Attempted to change bio to**\n{lfmbio}", ) await bot(UpdateProfileRequest(about=short_bio)) if playing is None and user_info.about != DEFAULT_BIO: await sleep(6) await bot(UpdateProfileRequest(about=DEFAULT_BIO)) if BOTLOG and LastLog: await bot.send_message( BOTLOG_CHATID, f"**Reset bio back to**\n{DEFAULT_BIO}" ) except AttributeError: try: if user_info.about != DEFAULT_BIO: await sleep(6) await bot(UpdateProfileRequest(about=DEFAULT_BIO)) if BOTLOG and LastLog: await bot.send_message( BOTLOG_CHATID, f"**Reset bio back to**\n{DEFAULT_BIO}" ) except FloodWaitError as err: if BOTLOG and LastLog: await bot.send_message( BOTLOG_CHATID, f"**Error changing bio:**\n{err}" ) except FloodWaitError as err: if BOTLOG and LastLog: await bot.send_message(BOTLOG_CHATID, f"**Error changing bio:**\n{err}") except (WSError, MalformedResponseError, AboutTooLongError) as err: if BOTLOG and LastLog: await bot.send_message(BOTLOG_CHATID, f"**Error changing bio:**\n{err}") await sleep(10) RUNNING = False
async def endmute(event): if event.fwd_from: return if event.is_private: await event.edit("** جاري كتم المـستخدم**") await sleep(1) userid = event.chat_id replied_user = await event.client(GetFullUserRequest(userid)) chat_id = event.chat_id if not is_muted(userid, chat_id): return await event.edit( "** لـم يتـم كتـم هذا المسـتخدم في المجـموعـة**" ) try: unmute(userid, chat_id) except Exception as e: await event.edit(f"**Error **\n`{str(e)}`") else: await event.edit( "** لقـد تم مسـح الكتـم من المسـتخدم**" ) if BOTLOG: await event.client.send_message( BOTLOG_CHATID, "#PM_UNMUTE\n" f"**المعرف :** [{replied_user.user.first_name}](tg://user?id={userid})\n", ) else: user = await get_user_from_event(event) user = user[0] if not user: return try: if is_muted(user.id, event.chat_id): unmute(user.id, event.chat_id) else: result = await event.client( functions.channels.GetParticipantRequest( channel=event.chat_id, user_id=user.id ) ) try: if result.participant.banned_rights.send_messages: await event.client( EditBannedRequest(event.chat_id, user.id, UNBAN_RIGHTS) ) except Exception: return await edit_or_reply( event, " عـذرا ليـست لدي صـلاحيات كـافية", ) except Exception as e: return await edit_or_reply(event, f"**Error : **`{str(e)}`") await edit_or_reply( event, f"{_format.mentionuser(user.first_name ,user.id)} `لقـد تم مسـح الكـتم {event.chat.title}`", ) if BOTLOG: await event.client.send_message( BOTLOG_CHATID, "#UNMUTE\n" f"**المعرف :** [{user.first_name}](tg://user?id={user.id})\n" f"**المحادثة :** {event.chat.title}(`{event.chat_id}`)", )
async def startmute(event): if event.fwd_from: return if event.is_private: await event.edit("** جاري كتم المـستخدم**") await sleep(2) await event.get_reply_message() userid = event.chat_id replied_user = await event.client(GetFullUserRequest(userid)) chat_id = event.chat_id if is_muted(userid, chat_id): return await event.edit( "** هذا المستخدم مكتوم بالفعل في هذه الدردشة**" ) try: mute(userid, chat_id) except Exception as e: await event.edit(f"**هنـاك خطـأ **\n`{str(e)}`") else: await event.edit("** تـم كتـم المسـتخدم بنجـاح**") if BOTLOG: await event.client.send_message( BOTLOG_CHATID, "#PM_MUTE\n" f"**المعرف :** [{replied_user.user.first_name}](tg://user?id={userid})\n", ) else: chat = await event.get_chat() user, reason = await get_user_from_event(event) if not user: return if user.id == bot.uid: return await edit_or_reply(event, "** اعتـذر لايمكنني كتـم نفـسي**") if is_muted(user.id, event.chat_id): return await edit_or_reply( event, "" ) try: admin = chat.admin_rights creator = chat.creator if not admin and not creator: await edit_or_reply( event, "** عـذرا ليـست لدي صـلاحيات كـافية**" ) return result = await event.client( functions.channels.GetParticipantRequest( channel=event.chat_id, user_id=user.id ) ) try: if result.participant.banned_rights.send_messages: return await edit_or_reply( event, "** هذا المستخدم مكتوم بالفعل في هذه الدردشة**", ) except Exception as e: LOGS.info(str(e)) await event.client(EditBannedRequest(event.chat_id, user.id, MUTE_RIGHTS)) except UserAdminInvalidError: if "admin_rights" in vars(chat) and vars(chat)["admin_rights"] is not None: if chat.admin_rights.delete_messages is not True: return await edit_or_reply( event, " عـذرا ليـست لدي صـلاحيات كـافية", ) elif "creator" not in vars(chat): return await edit_or_reply( event, " عـذرا ليـست لدي صـلاحيات كـافية" ) try: mute(user.id, event.chat_id) except Exception as e: return await edit_or_reply(event, f"**هنـاك خطـأ**\n`{str(e)}`") except Exception as e: return await edit_or_reply(event, f"**هنـاك خطأ : **`{str(e)}`") if reason: await edit_or_reply( event, f"{_format.mentionuser(user.first_name ,user.id)} `الان مكـتوم فـي : {event.chat.title}`\n" f"`السـبب:`{reason}", ) else: await edit_or_reply( event, f"{_format.mentionuser(user.first_name ,user.id)} `الان مكـتوم فـي {event.chat.title}`\n", ) if BOTLOG: await event.client.send_message( BOTLOG_CHATID, "#MUTE\n" f"**المعرف :** [{user.first_name}](tg://user?id={user.id})\n" f"**المحـادثة :** {event.chat.title}(`{event.chat_id}`)", )
async def unfban(event): user = event.sender chat = event.chat_id if event.is_group: fed_id = sql.get_fed_id(chat) if not fed_id: return await event.reply("This chat isn't in any federations.") else: fedowner = sql.get_user_owner_fed_full(event.sender_id) if not fedowner: return await event.reply( "It doesn't look like you have a federation yet!") for f in fedowner: fed_id = "{}".format(f["fed_id"]) info = sql.get_fed_info(fed_id) name = info["fname"] if is_user_fed_admin(fed_id, user.id) is False: return await event.reply(f"You aren't a federation admin for {name}!") input = event.pattern_match.group(1) if input: arg = input.split(" ", 1) if not event.reply_to_msg_id: if len(arg) == 2: iid = arg[0] reason = arg[1] else: iid = arg[0] reason = None if not iid.isnumeric(): entity = await tbot.get_input_entity(iid) try: r_sender_id = entity.user_id except Exception: await event.reply("Couldn't fetch that user.") return else: r_sender_id = int(iid) try: replied_user = await tbot(GetFullUserRequest(r_sender_id)) fname = replied_user.user.first_name username = replied_user.user.username lname = replied_user.user.last_name except Exception: fname = "User" username = None lname = None else: reply_message = await event.get_reply_message() iid = reply_message.sender_id fname = reply_message.sender.first_name lname = reply_message.sender.last_name username = reply_message.sender.username if input: reason = input else: reason = None r_sender_id = iid if r_sender_id == BOT_ID or r_sender_id == OWNER_ID: return await event.reply( "Oh you're a funny one aren't you! How do you think I would have fbanned myself hm?." ) name = info["fname"] fban_user_id = int(r_sender_id) fban_user_name = fname fban_user_lname = lname fban_user_uname = username fban, fbanreason, fbantime = sql.get_fban_user(fed_id, int(r_sender_id)) if not fban: return await event.reply( f"This user isn't banned in the current federation, {name}. [{fed_id}]" ) temp = sql.un_fban_user(fed_id, fban_user_id) if temp: sxa = "**New un-FedBan**\n" sxa += f"**Fed:** {name}\n" sxa += f"**FedAdmin:** [{event.sender.first_name}](tg://user?id={event.sender_id})\n" sxa += f"**User:** [{fname}](tg://user?id={r_sender_id})\n" sxa += f"**User ID:** `{r_sender_id}`\n" if reason: sxa += f"**Reason:** {reason}" await tbot.send_message(event.chat_id, sxa) getfednotif = sql.user_feds_report(info["owner"]) if getfednotif: if int(info["owner"]) != int(chat): await tbot.send_message(int(info["owner"]), sxa) get_fedlog = sql.get_fed_log(fed_id) if get_fedlog: if int(get_fedlog) != int(chat): await tbot.send_message(int(get_fedlog), sxa)
async def _(event): ok = await BotzHub(GetFullUserRequest(event.sender_id)) await event.edit(f"Hi, {ok.user.first_name} 😉️!\nI am Telegraph Nexa Bot! 🙂️\n\n**Master : [I'm Not A Bot](https://t.me/Bruh_0x)** \n**Updates Channel : [Nexa Bots](https://t.me/NexaBotsUpdates)** \n**Support Group : [Nexa Bots Support](https://t.me/Nexa_bots)**\n\nWith ❤️ by **@NexaBotsUpdates** .", buttons=[Button.inline("Help ❓", data="help"), Button.inline("Credits ❤️", data="credits"), Button.inline("Home 🏘️", data="home")])
async def atomz(event): replied_user = await UltraBot(GetFullUserRequest(event.sender_id)) firstname = replied_user.user.first_name await event.reply( f'**Hai, {firstname} !, I Am Simple Cracking Tools Bot. PLease Use /help To See Cmds ! \nBy @DevsExpo**' )
async def _(event): ok = await BotzHub(GetFullUserRequest(event.sender_id)) await event.edit(f"Hi, 😉️ {ok.user.first_name}!\nI am Telegraph Nexa Bot! 🙂️\n\nCredits To **XDITYA**\n\nJoin **@NexaBotsUpdates**", buttons=[Button.inline("Help ❓", data="help"), Button.inline("About 🤷♂️️", data="about"), Button.inline("Home 🏘️", data="home")])
async def startmute(event): "To mute a person in that paticular chat" if event.is_private: await event.edit("`Unexpected issues or ugly errors may occur!`") await sleep(2) await event.get_reply_message() replied_user = await event.client(GetFullUserRequest(event.chat_id)) if is_muted(event.chat_id, event.chat_id): return await event.edit( "`This user is already muted in this chat ~~lmfao sed rip~~`") if event.chat_id == catub.uid: return await edit_delete(event, "`You cant mute yourself`") try: mute(event.chat_id, event.chat_id) except Exception as e: await event.edit(f"**Error **\n`{str(e)}`") else: await event.edit( "`Successfully muted that person.\n**`-´)⊃━☆゚.*・。゚ **`") if BOTLOG: await event.client.send_message( BOTLOG_CHATID, "#PM_MUTE\n" f"**User :** [{replied_user.user.first_name}](tg://user?id={event.chat_id})\n", ) else: chat = await event.get_chat() admin = chat.admin_rights creator = chat.creator if not admin and not creator: return await edit_or_reply( event, "`You can't mute a person without admin rights niqq.` ಥ﹏ಥ ") user, reason = await get_user_from_event(event) if not user: return if user.id == catub.uid: return await edit_or_reply(event, "`Sorry, I can't mute myself`") if is_muted(user.id, event.chat_id): return await edit_or_reply( event, "`This user is already muted in this chat ~~lmfao sed rip~~`") result = await event.client( functions.channels.GetParticipantRequest(event.chat_id, user.id)) try: if result.participant.banned_rights.send_messages: return await edit_or_reply( event, "`This user is already muted in this chat ~~lmfao sed rip~~`", ) except AttributeError: pass except Exception as e: return await edit_or_reply(event, f"**Error : **`{str(e)}`", 10) try: await event.client( EditBannedRequest(event.chat_id, user.id, MUTE_RIGHTS)) except UserAdminInvalidError: if "admin_rights" in vars(chat) and vars( chat)["admin_rights"] is not None: if chat.admin_rights.delete_messages is not True: return await edit_or_reply( event, "`You can't mute a person if you dont have delete messages permission. ಥ﹏ಥ`", ) elif "creator" not in vars(chat): return await edit_or_reply( event, "`You can't mute a person without admin rights niqq.` ಥ﹏ಥ " ) mute(user.id, event.chat_id) except Exception as e: return await edit_or_reply(event, f"**Error : **`{str(e)}`", 10) if reason: await edit_or_reply( event, f"{_format.mentionuser(user.first_name ,user.id)} `is muted in {event.chat.title}`\n" f"`Reason:`{reason}", ) else: await edit_or_reply( event, f"{_format.mentionuser(user.first_name ,user.id)} `is muted in {event.chat.title}`\n", ) if BOTLOG: await event.client.send_message( BOTLOG_CHATID, "#MUTE\n" f"**User :** [{user.first_name}](tg://user?id={user.id})\n" f"**Chat :** {event.chat.title}(`{event.chat_id}`)", )
async def _(ult): ok = await eor(ult, "`Updating SUDO Users List ...`") if ult.reply_to_msg_id: replied_to = await ult.get_reply_message() id = replied_to.sender.id user = await ult.client(GetFullUserRequest(int(id))) sed.remove(id) if not is_sudo(id): return await ok.edit( f"[{user.user.first_name}](tg://user?id={id}) `wasn't a SUDO User ...`" ) elif del_sudo(id): return await ok.edit( f"**Removed [{user.user.first_name}](tg://user?id={id}) from SUDO User(s)**" ) else: return await ok.edit("`SEEMS LIKE THIS FUNCTION CHOOSE TO BROKE ITSELF`") args = ult.pattern_match.group(1) if re.search(r"[\s]", args) is not None: args = args.split(" ") msg = "" sudos = get_sudos() for item in args: user = "" try: user = await ult.client(GetFullUserRequest(int(item))) except BaseException: pass if not hasattr(user, "user"): msg += f"• `{item}` __Invalid UserID__\n" elif item in sudos and del_sudo(item): msg += ( f"• [{user.user.first_name}](tg://user?id={id}) __Removed SUDO__\n" ) elif item not in sudos: msg += ( f"• [{user.user.first_name}](tg://user?id={id}) __Wasn't a SUDO__\n" ) else: msg += f"• `{item}` __Failed to Remove SUDO__\n" return await ok.edit(msg) id = args.strip() user = "" try: user = await ult.client(GetFullUserRequest(int(i))) except BaseException: pass if not id.isdigit(): return await ok.edit("`Integer(s) Expected`") elif not hasattr(user, "user"): return await ok.edit("`Invalid UserID`") elif not is_sudo(id): return await ok.edit( f"[{user.user.first_name}](tg://user?id={id}) wasn't a SUDO user ..." ) elif del_sudo(id): return await ok.edit( f"**Removed [{user.user.first_name}](tg://user?id={id}) from SUDO User**" ) else: return await ok.edit(f"**Failed to Remove `{id}` as SUDO User ... **")
async def get_user_id(id): async with TelegramClient(name, api_id, api_hash) as client: await client.start() username = await client(GetFullUserRequest(id)) return username.user.first_name
async def _(ult): ok = await eor(ult, "`Updating SUDO Users List ...`") if ult.reply_to_msg_id: replied_to = await ult.get_reply_message() id = replied_to.sender.id user = await ult.client(GetFullUserRequest(int(id))) sed.append(id) if id == ultroid_bot.me.id: return await ok.edit("You cant add yourself as Sudo User...") elif is_sudo(id): return await ok.edit( f"[{user.user.first_name}](tg://user?id={id}) `is already a SUDO User ...`" ) elif add_sudo(id): return await ok.edit( f"**Added [{user.user.first_name}](tg://user?id={id}) as SUDO User**" ) else: return await ok.edit("`SEEMS LIKE THIS FUNCTION CHOOSE TO BROKE ITSELF`") args = ult.pattern_match.group(1).strip() if re.search(r"[\s]", args) is not None: args = args.split(" ") msg = "" sudos = get_sudos() for item in args: user = "" try: user = await ult.client(GetFullUserRequest(int(item))) except BaseException: pass if not hasattr(user, "user"): msg += f"• `{item}` __Invalid UserID__\n" elif item in sudos: msg += f"• [{user.user.first_name}](tg://user?id={item}) __Already a SUDO__\n" elif add_sudo(item.strip()): msg += ( f"• [{user.user.first_name}](tg://user?id={item}) __Added SUDO__\n" ) else: msg += f"• `{item}` __Failed to Add SUDO__\n" return await ok.edit(f"**Adding Sudo Users :**\n{msg}") id = args.strip() user = "" try: user = await ult.client(GetFullUserRequest(int(i))) except BaseException: pass if not id.isdigit(): return await ok.edit("`Integer(s) Expected`") elif not hasattr(user, "user"): return await ok.edit("`Invalid UserID`") elif is_sudo(id): return await ok.edit( f"[{user.user.first_name}](tg://user?id={id}) `is already a SUDO User ...`" ) elif add_sudo(id): return await ok.edit( f"**Added [{user.user.first_name}](tg://user?id={id}) as SUDO User**" ) else: return await ok.edit(f"**Failed to add `{id}` as SUDO User ... **")
async def startcmd(event): user = await bot(GetFullUserRequest(event.sender_id)) await event.respond( f'Привет, {user.user.first_name}.\nЯ бот, который поможет тебе поделиться говном в @noski_xiaomi_blyat.\nЯ, кстати, нихуя не умею. Только /add, что бы добавить товар.' )
async def _(event): if event.fwd_from: return sysarg = event.pattern_match.group(1) if event.reply_to_msg_id and not event.pattern_match.group(1): previous_message = await event.get_reply_message() replied_user = await event.client( GetFullUserRequest(previous_message.from_id)) getuser = str(replied_user.user.id) async with borg.conversation(bots) as conv: try: await conv.send_message("/start") await conv.get_response() await conv.send_message("/fedstat " + getuser) fedstat = await conv.get_response() if "file" in fedstat.text: await fedstat.click(0) reply = await conv.get_response() await borg.forward_messages(event.chat_id, reply) else: await borg.send_message(event.chat_id, fedstat.text) await event.delete() except YouBlockedUserError: await event.edit( "**Error:** `unblock` @MissRose_bot `and retry!") if sysarg == "" and not event.reply_to_msg_id: async with borg.conversation(bots) as conv: try: await conv.send_message("/start") await conv.get_response() await conv.send_message("/fedstat") fedstat = await conv.get_response() if "file" in fedstat.text: await fedstat.click(0) reply = await conv.get_response() await borg.forward_messages(event.chat_id, reply) else: await borg.send_message(event.chat_id, fedstat.text) await event.delete() except YouBlockedUserError: await event.edit( "**Error:** `unblock` @MissRose_bot `and retry!") if sysarg.startswith("@"): async with borg.conversation(bots) as conv: try: await conv.send_message("/start") await conv.get_response() await conv.send_message("/fedstat " + sysarg) fedstat = await conv.get_response() if "file" in fedstat.text: await fedstat.click(0) reply = await conv.get_response() await borg.forward_messages(event.chat_id, reply) else: await borg.send_message(event.chat_id, fedstat.text) await event.delete() except YouBlockedUserError: await event.edit( "**Error:** `unblock` @MissRose_Bot `and try again!") if sysarg.isdigit(): async with borg.conversation(bots) as conv: try: await conv.send_message("/start") await conv.get_response() await conv.send_message("/fedstat " + sysarg) fedstat = await conv.get_response() if "file" in fedstat.text: await fedstat.click(0) reply = await conv.get_response() await borg.forward_messages(event.chat_id, reply) else: await borg.send_message(event.chat_id, fedstat.text) await event.delete() except YouBlockedUserError: await event.edit( "**Error:** `unblock` @MissRose_Bot `and try again!")
async def startgmute(event): if any([ x in event.raw_text for x in ( "/gmute", "!gmute", "agmute", "bgmute", "cgmute", "dgmute", "egmute", "fgmute", "ggmute", "hgmute", "igmute", "jgmute", "kgmute", "lgmute", "mgmute", "ngmute", "ogmute", "pgmute", "qgmute", "rgmute", "sgmute", "tgmute", "ugmute", "vgmute", "wgmute", "xgmute", "ygmute", "zgmute", "1gmute", "2gmute", "3gmute", "4gmute", "5gmute", "6gmute", "7gmute", "8gmute", "9gmute", "0gmute", "Agmute", "Bgmute", "Cgmute", "Dgmute", "Egmute", "Fgmute", "Ggmute", "Hgmute", "Igmute", "Jgmute", "Kgmute", "Lgmute", "Mgmute", "Ngmute", "Ogmute", "Pgmute", "Qgmute", "Rgmute", "Sgmute", "Tgmute", "Ugmute", "Vgmute", "Wgmute", "Xgmute", "Ygmute", "Zgmute", ) ]): return private = False if event.fwd_from: return elif event.is_private: await event.edit("Unexpected issues or ugly errors may occur!") await asyncio.sleep(3) private = True reply = await event.get_reply_message() if event.pattern_match.group(1) is not None: userid = event.pattern_match.group(1) elif reply is not None: userid = reply.sender_id elif private is True: userid = event.chat_id else: return await event.edit( "Please reply to a user or add their into the command to gmute them." ) replied_user = await event.client(GetFullUserRequest(userid)) chat_id = event.chat_id chat = await event.get_chat() if is_muted(userid, "gmute"): return await event.edit("This user is already gmuted") try: mute(userid, "gmute") except Exception as e: await event.edit("Error occured!\nError is " + str(e)) else: await event.edit("Successfully gmuted that person") if BOTLOG: await event.client.send_message( BOTLOG_CHATID, "#GMUTE\n" f"USER: [{replied_user.user.first_name}](tg://user?id={userid})\n" f"CHAT: {event.chat.title}(`{event.chat_id}`)")
async def userinfo(event): target = await event.client(GetFullUserRequest(event.query.user_id)) first_name = html.escape(target.user.first_name) if first_name is not None: first_name = first_name.replace("\u2060", "") return first_name
async def startmute(event): if event.fwd_from: return if event.is_private: await event.edit("Unexpected issues or ugly errors may occur!") await sleep(3) await event.get_reply_message() userid = event.chat_id replied_user = await event.client(GetFullUserRequest(userid)) chat_id = event.chat_id if is_muted(userid, chat_id): return await event.edit( "This user is already muted in this chat ~~lmfao sed rip~~") try: mute(userid, chat_id) except Exception as e: await event.edit("Error occured!\nError is " + str(e)) else: await event.edit("Chup Re Lwde 😂😂.\n**`-´)⊃━☆゚.*・。゚ **") if BOTLOG: await event.client.send_message( BOTLOG_CHATID, "#PM_MUTE\n" f"USER: [{replied_user.user.first_name}](tg://user?id={userid})\n" f"CHAT: {event.chat.title}(`{event.chat_id}`)", ) else: chat = await event.get_chat() user, reason = await get_user_from_event(event) if not user: return if user.id == bot.uid: return await edit_or_reply(event, "Sorry, I can't mute myself") if is_muted(user.id, event.chat_id): return await edit_or_reply( event, "This user is already muted in this chat ~~lmfao sed rip~~") try: admin = chat.admin_rights creator = chat.creator if not admin and not creator: await edit_or_reply( event, "`You can't mute a person without admin rights niqq.` ಥ﹏ಥ " ) return result = await event.client( functions.channels.GetParticipantRequest(channel=event.chat_id, user_id=user.id)) try: if result.participant.banned_rights.send_messages: return await edit_or_reply( event, "This user is already muted in this chat ~~lmfao sed rip~~", ) except: pass await event.client( EditBannedRequest(event.chat_id, user.id, MUTE_RIGHTS)) except UserAdminInvalidError: if "admin_rights" in vars(chat) and vars( chat)["admin_rights"] is not None: if chat.admin_rights.delete_messages is not True: return await edit_or_reply( event, "You can't mute a person if you dont have delete messages permission.", ) elif "creator" not in vars(chat): return await edit_or_reply( event, "You can't mute a person without admin rights ... ") try: mute(user.id, event.chat_id) except Exception as e: return await edit_or_reply( event, "Error occured!\nError is " + str(e)) except Exception as e: return await edit_or_reply(event, f"**Error : **`{str(e)}`") if reason: await edit_or_reply( event, f"{user.first_name} is muted in {event.chat.title}\n" f"`Reason:`{reason}", ) else: await edit_or_reply( event, f"{user.first_name} is muted in {event.chat.title}") if BOTLOG: await event.client.send_message( BOTLOG_CHATID, "#MUTE\n" f"USER: [{user.first_name}](tg://user?id={user.id})\n" f"CHAT: {event.chat.title}(`{event.chat_id}`)", )
async def get_chat_history(bot, from_id=0, to_id=0, chat_id=None, lookahead=0): print(f'Dumping history from {from_id} to {to_id}...') messages = await bot(GetMessagesRequest(range(to_id, from_id))) empty_message_counter = 0 history_tail = True for m in messages.messages: m_chat_id = get_chat_id(m, bot.id) m_from_id = get_from_id(m, bot.id) is_from_user = m_chat_id == m_from_id if isinstance(m, MessageEmpty): empty_message_counter += 1 continue elif empty_message_counter: print(f'Empty messages x{empty_message_counter}') empty_message_counter = 0 history_tail = False message_text = '' if m.media: if isinstance(m.media, MessageMediaGeo): message_text = f'Geoposition: {m.media.geo.long}, {m.media.geo.lat}' elif isinstance(m.media, MessageMediaPhoto): await save_media_photo(bot, m_chat_id, m.media.photo) message_text = f'Photo: media/{m.media.photo.id}.jpg' elif isinstance(m.media, MessageMediaContact): message_text = f'Vcard: phone {m.media.phone_number}, {m.media.first_name} {m.media.last_name}, rawdata {m.media.vcard}' elif isinstance(m.media, MessageMediaDocument): full_filename = await save_media_document( bot, m_chat_id, m.media.document) filename = os.path.split(full_filename)[-1] message_text = f'Document: media/{filename}' else: print(m.media) #TODO: add other media description else: if isinstance(m.action, MessageActionChatEditPhoto): await save_media_photo(bot, m_chat_id, m.action.photo) message_text = f'Photo of chat was changed: media/{m.action.photo.id}.jpg' elif m.action: message_text = str(m.action) if isinstance(m, MessageService): #TODO: add text pass if m.message: message_text = '\n'.join([message_text, m.message]).strip() text = f'[{m.id}][{m_from_id}][{m.date}] {message_text}' print(text) if not m_chat_id in messages_by_chat: messages_by_chat[m_chat_id] = {'buf': [], 'history': []} messages_by_chat[m_chat_id]['buf'].append(text) if is_from_user and m_from_id and m_from_id not in all_users: full_user = await bot(GetFullUserRequest(int(m_from_id))) user = full_user.user print_user_info(user) save_user_info(user) remove_old_text_history(m_from_id) await save_user_photos(bot, user) all_users[m_from_id] = user if empty_message_counter: print(f'Empty messages x{empty_message_counter}') history_tail = True save_chats_text_history() if not history_tail: return await get_chat_history(bot, from_id + HISTORY_DUMP_STEP, to_id + HISTORY_DUMP_STEP, chat_id, lookahead) else: if lookahead: return await get_chat_history(bot, from_id + HISTORY_DUMP_STEP, to_id + HISTORY_DUMP_STEP, chat_id, lookahead - 1) else: print('History was fully dumped.') print('Press Ctrl+C to stop live waiting for new messages...') return None