def sethook(bot, update, cmd=None): if not cmd: return blacklist = utils.dbget('hook') if blacklist is not None: if str(update.message.from_user.id) in blacklist: update.message.reply_text( emojize(choice(utils.blacklist_strings), use_aliases=True)) return check_black = utils.dbget('notarget') hook_vk_user = get_user(cmd[0]) if isinstance(hook_vk_user, str): update.message.reply_text( emojize('Ошибка :disappointed:', use_aliases=True)) return reply_text = emojize('Хорошо :ok_hand:', use_aliases=True) if check_black is not None: if str(hook_vk_user['id']) in check_black: reply_text = hook_vk_user['first_name'] + ' ' + hook_vk_user[ 'last_name'] + ' помечен как спамер!\nЕсли этот человек будет спамить вам, вы можете ввести /delhook ' + str( hook_vk_user['id'] ) + ' чтобы перестать получать от него сообшения' utils.dbadd(hook_vk_user['id'], update.message.chat.id) update.message.reply_text(reply_text) keen.add_event("set_hook", { "by_user": update.message.from_user.id, "req_user": cmd[0] })
def button(bot, update): query = update.callback_query bl = utils.dbget('button') if bl is not None: if str(query.from_user.id) in bl: return user_id, page = query.data.split('|') try: keyboard = [ InlineKeyboardButton("<", callback_data=user_id + '|' + str(int(page) - 1)), InlineKeyboardButton(">", callback_data=user_id + '|' + str(int(page) + 1)) ] if int(page) == 0: keyboard.pop(0) reply_markup = InlineKeyboardMarkup([keyboard]) msg = history_text(user_id, int(page)) bot.editMessageText(chat_id=query.message.chat_id, text=msg, parse_mode='HTML', reply_markup=reply_markup, message_id=query.message.message_id) keen.add_event("history_button", {"req_user": user_id}) except Exception: return
def send(bot, update, cmd=None): blacklist = utils.dbget('send') if blacklist is not None: if str(update.message.from_user.id) in blacklist: update.message.reply_text( emojize(choice(utils.blacklist_strings), use_aliases=True)) return if not cmd: return user = get_user(cmd[0]) vkb = utils.dbget('vkblacklist') if vkb is not None: if str(user['id']) in vkb: update.message.reply_text( 'Вы не можете отправлять сообщения этому пользователю') tg.send_message( admin, str(update.message.from_user.id) + '\n' + str(update.message.text)) return data = '' try: data = api.messages.send(peer_id=user['id'], message=cmd[1]) except exceptions.VkException as exception: data = str(exception) except TypeError: data = emojize('Что-то пошло не так :confused:', use_aliases=True) # if not enough args finally: if isinstance(data, int): full_name = utils.escapize(user['first_name'] + ' ' + user['last_name']) t = '<b>' + full_name + ' <<<</b>\n' + utils.escapize( cmd[1]) update.message.reply_text(t, parse_mode='HTML', disable_web_page_preview=True) tg.send_message(log_channel, t, 'HTML', True) utils.dbadd('activity', '✉️ ' + full_name + ' - ' + str(user['id'])) keen.add_event("sended", { "by_user": update.message.from_user.id, "to_user": user['id'] }) else: update.message.reply_text(str(data))
def parse_message(message_object, callback): user_id = message_object['user_id'] text = message_object['body'] targets = utils.dbget(user_id) check_black = utils.dbget('notarget') if targets is None: if check_black is not None: if str(user_id) in check_black: return else: targets = [log_channel] else: targets = [log_channel] else: if check_black is not None: if str(user_id) not in check_black: targets.append(log_channel) attachments = [] if 'attachments' in message_object: for a in message_object['attachments']: if a['type'] == 'photo': keys = [k for k, v in a['photo'].items()] best_num = max( int(item.split('_')[1]) for item in keys if item.startswith('photo_')) url = a['photo']['photo_' + str(best_num)] photo = requests.get(url) file_name = str(a['photo']['id']) + ' ' + url.split('/')[-1] with open(file_name, 'wb') as pic: pic.write(photo.content) attachments.append({'type': 'photo', 'pic': file_name}) elif a['type'] == 'sticker': pass elif a['type'] == 'wall': pass elif a['type'] == 'doc': pass elif a['type'] == 'audio': pass for t in targets: callback(t, user_id, text, attachments) for a in attachments: os.remove(a['pic'])
def check_unread(): dialogs = api.messages.getDialogs(count=200, unread=True) if dialogs['count'] > 0: msg_ids = [] d = utils.plural(dialogs['count']) response = '<b>' + str( dialogs['count'] ) + ' ' + d + ' с непрочитанными сообщениями:</b>\n' for i in dialogs['items']: sleep(2) user_id = i['message']['user_id'] msg_ids.append(i['message']['id']) try: user = api.users.get(user_ids=user_id)[0] full_name = utils.escapize(user['first_name'] + ' ' + user['last_name']) response += full_name + ' ' + str(user_id) + '\n' except exceptions.VkException: pass # User notification if user_id > 0: targets = utils.dbget(user_id) if targets is not None: for t in targets: u = api.users.get(user_ids=user_id, name_case='gen')[0] u_nom = api.users.get(user_ids=user_id)[0] full_name = utils.escapize(u['first_name'] + ' ' + u['last_name']) full_name_nom = utils.escapize(u_nom['first_name'] + ' ' + u_nom['last_name']) sud = str(u_nom['id']) utils.dbadd('activity', '✉️ ' + full_name_nom + ' - ' + sud) text = 'Есть новые сообщения от <b>' + full_name + '.</b> Id: ' + sud + '\nВведите <code>/d ' + sud + '</code> чтобы получить историю сообщений' try: tg.sendMessage(chat_id=t, text=text, parse_mode='HTML', disable_web_page_preview=True) except Exception as e: et = 'Exception:\n' + str( e ) + '\nIn check_unread while sending to target - ' + str( t) # noinspection PyTypeChecker tg.send_message(admin, et) sleep(2) tg.send_message(log_channel, response, 'HTML', True) try: api.messages.markAsRead(message_ids=msg_ids) except exceptions.VkException as e: ete = 'Exception:\n' + str( e) + '\nIn check_unread while markAsRead' # noinspection PyTypeChecker tg.send_message(admin, ete)
async def mangalogger(client): info = u.dbget('chandumps', 'id,guildid,channelid,lastmessageid', 'outdir is null') for n in info: mangalog[n['channelid']] = {} known = u.dbget('dupeslist') for n in known: mangalog[n['chid']][n['maid']] = n['meid'] for entry in info: chan = client.get_channel(int(entry['channelid'])) if not chan: u.trace(f"Can't into channel {entry['channelid']}") continue if entry['lastmessageid'] is None: msgs = await chan.history(limit=None, oldest_first=True).flatten() else: msg = await chan.fetch_message(int(entry['lastmessageid'])) msgs = await chan.history(limit=None, oldest_first=True, after=msg.created_at).flatten() if not msgs: u.trace(f'Since nothing to do in {chan.id}, why should I get up?') continue cleanup = [] for msg in msgs: dat = parseMD(msg.content, chan.id, msg.id) if dat in (-1, 1): cleanup.append(msg) if type(dat) == str: await chan.send(dat) cleanup.append(msg) cuids = [n.id for n in cleanup] cleanup = await chan.purge( limit=None, check=lambda x: x.id in cuids ) # A builtin convenience wrapper. Only in Python. :^) if len(cleanup) < len(cuids): u.dbalter('chandumps', {'lastmessageid': msgs[-1].id}, f'id="{entry["id"]}"') # Since we left some messages if len(cleanup) > 0: conf = await chan.send( f"Cleaned up {len(cleanup)} non-manga/dupe messages") await asyncio.sleep(5) await conf.delete()
def blacklist_control(bot, update, cmd=None): if not cmd: return try: if cmd[0] == 'add': for i in cmd[1].split(): utils.dbadd(i, str(update.message.reply_to_message.from_user.id)) tg.send_message(admin, str(utils.dbget(i))) sleep(2) if cmd[0] == 'del': for i in cmd[1].split(): utils.dbdel(i, str(update.message.reply_to_message.from_user.id)) tg.send_message(admin, str(utils.dbget(i))) sleep(2) update.message.reply_text('Успешно') except Exception as e: tg.send_message(admin, str(e)) update.message.reply_text('Nope.')
def delhook(bot, update, cmd=None): if not cmd: return blacklist = utils.dbget('hook') if blacklist is not None: if str(update.message.from_user.id) in blacklist: update.message.reply_text( emojize(choice(utils.blacklist_strings), use_aliases=True)) return try: hook_vk_user = api.users.get(user_ids=cmd[0])[0]['id'] except exceptions.VkException: update.message.reply_text( emojize('Ошибка :disappointed:', use_aliases=True)) return utils.dbdel(hook_vk_user, update.message.chat.id) print(str(utils.dbget(hook_vk_user))) update.message.reply_text(emojize('Ок :dash:', use_aliases=True)) keen.add_event("del_hook", { "by_user": update.message.from_user.id, "req_user": cmd[0] })
def like(bot, update, cmd=None): print('Call like(): ' + str(update.message.text)) blacklist = utils.dbget('like') if blacklist is not None: if str(update.message.from_user.id) in blacklist: update.message.reply_text( emojize(choice(utils.blacklist_strings), use_aliases=True)) return if not cmd: return try: user = api.users.get(user_ids=cmd[0])[0] owner = user['id'] name = user['first_name'] + ' ' + user['last_name'] except exceptions.VkException: group = api.groups.getById(group_id=cmd[0])[0] owner = 0 - group['id'] name = group['name'] print('calling db') available = utils.db_like(update.message.from_user.id) print(str(available) + ' likes for ' + str(update.message.from_user.id)) count = 10 if available >= 10 else available if count <= 0: update.message.reply_text( emojize('У вас не осталось сердечек :disappointed:', use_aliases=True)) keen.add_event("not_enough_user_likes", {"by_user": update.message.from_user.id}) return elif utils.limits() <= count: update.message.reply_text( emojize('Исчерапан дневной лимит бота :disappointed:', use_aliases=True)) keen.add_event("not_enough_global_likes", {"by_user": update.message.from_user.id}) return else: q.put([ owner, update.message.chat.id, name, count, update.message.from_user.id, update.message.message_id ]) update.message.reply_text( emojize('Ок, выполняю :sparkling_heart:', use_aliases=True)) utils.dbadd('activity', '❤️️ ' + name + ' - ' + str(owner))
def history(bot, update, cmd=None): bl = utils.dbget('history') if bl is not None: if str(update.message.from_user.id) in bl: update.message.reply_text( emojize(choice(utils.blacklist_strings), use_aliases=True)) return if not cmd: return try: keyboard = [[ InlineKeyboardButton(">", callback_data=str(cmd[0]) + '|1') ]] reply_markup = InlineKeyboardMarkup(keyboard) msg = history_text(cmd[0], 0) update.message.reply_text(msg, parse_mode='HTML', reply_markup=reply_markup) except Exception as e: update.message.reply_text(e) return
async def storylogger(client): info = u.dbget('chandumps', 'id, guildid, channelid, lastmessageid, outdir', 'outdir is not null') for entry in info: a = client.get_channel(int(entry['channelid'])) if not a: u.trace(f"Can't into channel {entry['channelid']}") continue #Have to strcmp because guildid could be None, which can't int() if not str(a.guild.id) == entry['guildid']: if entry['guildid'] is None: a = discord.utils.find( lambda c: c.id == int(entry['channelid']), client.private_channels) else: a = client.get_guild(int(entry['guildid'])).get_channel( int(entry['channelid'])) try: if entry['lastmessageid'] is None: #Lag time msgs = await a.history(limit=None, oldest_first=True).flatten() else: msg = await a.fetch_message(int(entry['lastmessageid'])) msgs = await a.history(limit=None, oldest_first=True, after=msg.created_at).flatten() except Forbidden: pass if msgs: story = [n.content for n in msgs] u.dbalter('chandumps', {'lastmessageid': msgs[-1].id}, f'id="{entry["id"]}"') #It is now that I realise that outdir is actually just an outfile. with open(entry['outdir'], 'a') as out: out.write(' ' + ' '.join(story))
async def deduper(client, msg): if msg.channel.id not in [ n['channelid'] for n in u.dbget('chandumps', 'channelid', 'outdir is null') ] or msg.author.bot: return dat = parseMD(msg.content, msg.channel.id, msg.id) if type(dat) == str: await msg.channel.send(dat) await msg.delete() return # Correct from chapter to title if dat == -1: msg2 = "Not an MD link" elif dat == 1: msg2 = "Duplicate link" if dat in (-1, 1): msg2 = await msg.channel.send(msg2) try: await msg.delete() except: pass await asyncio.sleep(5) await msg2.delete() elif dat == 0: u.dbalter('chandumps', {'lastmessageid': msg.id}, f'channelid="{msg.channel.id}"')
def fromvkblackdel(bot, update, cmd=None): if not cmd: return utils.dbdel('notarget', str(get_user(cmd[0])['id'])) tg.send_message(admin, str(utils.dbget('notarget')))
def vkblack(bot, update, cmd=None): if not cmd: return utils.dbadd('vkblacklist', str(get_user(cmd[0])['id'])) tg.send_message(admin, str(utils.dbget('vkblacklist')))
def activity(bot, update): data = utils.dbget('activity') t = '' for l in data: t += l + '\n' update.message.reply_text(t)