async def modUser(message, client, typ): split = message.content.split() correctUsageString = getUseString(typ + "user", client) if await checkMinArgs(message, 1, correctUsageString): return val = await checkInt(message, split[1], correctUsageString) if val is False: return user = client.get_user(val) if not user: return await sendError(message, f"{split[1]} is not a valid user id.", correctUsageString) config = utils.loadJson(globals.CONFIG_FILE) if typ == "add": if str(val) in config["ADMINS"]: return await message.channel.send( f"Error. {user.name} ({val}) is already a bot admin.") config["ADMINS"].append(str(val)) elif typ == "remove": if str(val) not in config["ADMINS"]: return await message.channel.send( f"Error. {user.name} ({val}) is not a bot admin.") config["ADMINS"] = [x for x in config['ADMINS'] if x != str(val)] lst = [] for x in config['ADMINS']: user = client.get_user(int(x)) if user: name = user.name else: name = "unknown" lst.append(f"`{name} ({x})`") await message.channel.send("Current admins: " + ", ".join(lst)) utils.dumpJson(config, globals.CONFIG_FILE)
async def modChannel(message, client, typ): split = message.content.split() correctUsageString = getUseString(typ + "channel", client) if await checkMinArgs(message, 1, correctUsageString): return val = await checkInt(message, split[1], correctUsageString) if val is False: return ch = client.get_channel(val) if not ch: return await sendError(message, f"{split[1]} is not a valid channel id.", correctUsageString) config = utils.loadJson(globals.CONFIG_FILE) if typ == "add": if str(val) in config["UPDATE_CHANNELS"]: return await message.channel.send( f"Error. <#{val}> is already an update channel.") config["UPDATE_CHANNELS"].append(str(val)) elif typ == "remove": if str(val) not in config["UPDATE_CHANNELS"]: return await message.channel.send( f"Error. <#{val}> is not an update channel.") config["UPDATE_CHANNELS"] = [ x for x in config['UPDATE_CHANNELS'] if x != str(val) ] lst = [f"<#{x}>" for x in config['UPDATE_CHANNELS']] await message.channel.send("Current update channels:" + ", ".join(lst)) utils.dumpJson(config, globals.CONFIG_FILE)
async def modMention(message, client, typ): split = message.content.split() correctUsageString = getUseString(typ + "role", client) if await checkMinArgs(message, 2, correctUsageString): return sid = await checkInt(message, split[1], correctUsageString) if sid is False: return rid = await checkInt(message, split[2], correctUsageString) if rid is False: return role = message.guild.get_role(int(rid)) if not role: return await sendError(message, f"{split[2]} is not a valid role id.", correctUsageString) mentions = utils.loadJson(globals.MENTION_FILE) sData = utils.loadJson(globals.SERIES_FILE) sName = str(sid) if str(sid) in sData: sName = f"{sData[str(sid)]['title']} ({sName})" if typ == "add": if str(sid) not in mentions: mentions[str(sid)] = [] if str(rid) in mentions[str(sid)]: return await message.channel.send( f"Error. `{role.name} ({rid})` is already a mentioned role for series `{sName}`." ) mentions[str(sid)].append(str(rid)) elif typ == "remove": if str(rid) not in mentions[str(sid)]: return await message.channel.send( f"Error. `{role.name} ({rid})` is not a mentioned role for series `{sName}`." ) mentions[str(sid)] = [ x for x in mentions[str(sid)] if str(x) != str(rid) ] lst = [] for x in mentions[str(sid)]: role = message.guild.get_role(int(rid)) if role: name = role.name else: continue name = "unknown" lst.append(f"`{name} ({x})`") await message.channel.send(f"Pinged roles for **`{sName}`**: " + ", ".join(lst)) utils.dumpJson(mentions, globals.MENTION_FILE)
async def handleUpdates(handler, cache, cacheFile): updateList = getUpdates() for update in updateList: id = update['chId'] + "|" + update['sId'] if id not in cache['seen']: print("Updating", update) #global lastDelay #if time.time() - lastDelay > delay: # print("Sleeping", delay) # lastDelay= time.time() updateSeriesData(update) await handler(update) cache['seen'].append(id) utils.dumpJson(cache, cacheFile)
def updateSeriesData(update): sid = update['sId'] data = utils.loadJson(globals.SERIES_FILE) if sid not in data or True: data[sid] = {} data[sid]['title'] = update['sName'] data[sid]['link'] = update['sLink'] data[sid]['cover'] = update['cover'] html = requests.get(update['sLink']).text soup = bs(html, 'html.parser') desc = soup.find( "div", class_="col-lg-9 col-md-8 col-xs-12 text-muted").findAll( text=True, recursive=False) desc = ''.join(desc).strip() data[sid]['description'] = desc utils.dumpJson(data, globals.SERIES_FILE)
async def setDiscordDelay(message, client): split = message.content.split() correctUsageString = getUseString("setdelay", client) if await checkMinArgs(message, 1, correctUsageString): return val = await checkInt(message, split[1], correctUsageString) if val is False: return if val < 0: return await sendError(message, "Delay interval must be positive", correctUsageString) config = utils.loadJson(globals.CONFIG_FILE) oldDelay = config["DISCORD_DELAY"] config["DISCORD_DELAY"] = val utils.dumpJson(config, globals.CONFIG_FILE) await message.channel.send( f"Updates are delayed `{val}` seconds (from `{oldDelay}`).")
async def updateHandler(update): while not client.is_ready(): await asyncio.sleep(1) #updateMessage= updateUtils.getUpdateMessage(update=update, mentionDict=MENTIONS) updateEmbed, mentions = updateUtils.getUpdateEmbed(update=update, mentionDict=MENTIONS) for chid in CONFIG['TEST_CHANNELS']: test = client.get_channel(int(chid)) if test: ss = f'Updating in {CONFIG["DISCORD_DELAY"]} seconds:\n```{json.dumps(update, indent=2)}```' print(ss) try: await test.send(ss) except discord.errors.Forbidden: pass await asyncio.sleep(delay=CONFIG['DISCORD_DELAY']) for chid in CONFIG['UPDATE_CHANNELS']: swapped = [] updateChannel = client.get_channel(int(chid)) if mentions: for roleId in mentions: role = updateChannel.guild.get_role(int(roleId)) if role: #and not role.mentionable: #await role.edit(mentionable=True) swapped.append(role) time.sleep(5) mentionString = f"<@&{'> <@&'.join(mentions)}> **{updateEmbed['title']}**" else: mentionString = "" try: # Edit last update if same series # todo: cleanup caching, chap numbering doEdit = False global CACHE, lastUpdate ls = CACHE['last_sent'] if "ids" in ls and str(chid) in ls['ids']\ and ls['update_content'][str(chid)]['sId'] == update['sId']\ and time.time() - float(ls['time'][str(chid)]) < CONFIG['SIMUL_UPDATE_INTERVAL']: if str(chid) not in lastUpdate: try: lastUpdate[str( chid)] = await updateChannel.fetch_message( int(ls['ids'][str(chid)])) except discord.NotFound as e: print("WARNING: Message", ls['ids'][str(chid)], "in", updateChannel.name, f"({updateChannel.id})", "not found.") CACHE['last_sent']['update_content'][str( chid)]['chId'] += ", " + update['chId'] e, __ = updateUtils.getUpdateEmbed( CACHE['last_sent']['update_content'][str(chid)], mentionDict=MENTIONS) await lastUpdate[str(chid) ].edit(embed=discord.Embed.from_dict(e)) doEdit = True CACHE['last_sent']['time'][str(chid)] = time.time() utils.dumpJson(dct=CACHE, path=globals.CACHE_FILE) if not doEdit: # await updateChannel.send(updateMessage) lastUpdate[str(chid)] = await updateChannel.send( embed=discord.Embed.from_dict(updateEmbed), content=mentionString) CACHE['last_sent']['ids'][str(chid)] = str( lastUpdate[str(chid)].id) CACHE['last_sent']['update_content'][str( chid)] = copy.deepcopy(update) CACHE['last_sent']['time'][str(chid)] = time.time() utils.dumpJson(CACHE, globals.CACHE_FILE) except Exception as e: print(e) time.sleep(5) for role in swapped: pass #await role.edit(mentionable=False)