async def messageHandler(message): p = DictionaryReader() if message.guild: await client.get_channel(p.logReportChannel()).send('{0.guild.name} - {0.channel.name} - {0.author} invoked {0.content}'.format(message)) else: await client.get_channel(p.logReportChannel()).send('PM - PM - {0.author} invoked {0.content}'.format(message)) if message.content.startswith(prefix+'fullupdate') or message.content.startswith(prefix+'update') or message.content.startswith(prefix+'channel'): await maintenanceMessages(message) elif message.content.startswith(prefix+'send'): await forwardMessage(message) elif message.content.startswith(prefix+'item'): await itemMessage(message) elif message.content.startswith(prefix+'pin') or message.content.startswith(prefix+'pins'): await sendPinMessages(message) elif message.content.startswith(prefix+'sub'): await RoleHandler.newsSubscription(client, message) await message.delete() elif message.content.startswith(prefix+'ban') or message.content.startswith(prefix+'info'): await adminControl(message) elif message.content.startswith(prefix+'stream'): print('StreamCommand') await RoleHandler.toggleStream(client, message) await message.delete() else: await generalMessage(message)
async def on_raw_reaction_remove(payload): r = DictionaryReader() if payload.channel_id == int(r.readEntry('subscriptionchannel', '')): await RoleHandler.newsSubscriptionRemove(client, payload.emoji, payload.user_id, payload.guild_id)
async def logAction(user, guild, action): r = DictionaryReader() channel = client.get_channel(int(r.actionLogChannel())) if guild and channel: await channel.send('[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] {1.name} - {0.name} {0.mention} ({0.id}) {2}'. format(user, guild, action))
async def toggleUserState(client, before, after): p = DictionaryReader() streamingRole = utils.find(lambda r: r.name == p.streamingRole(), before.guild.roles) # User doesn't have the streaming role, move along if streamingRole not in before.roles: return # Left the server if after is None: #print('left server') await RoleHandler.removeStream(client, before) # Role was removed elif streamingRole in before.roles and streamingRole not in after.roles: #print('role removed') await RoleHandler.removeStream(client, before) # Checks if the Game state changed or if the user isn't streaming # This or statement might be costly and subject to improvement elif before.activity != after.activity or after.activity is None or after.activity.type != ActivityType.streaming: p = DictionaryReader() if after.activity is None or after.activity.type != ActivityType.streaming: #print('stopped stream') # Stopped Streaming await RoleHandler.removeStream(client, after) elif after.activity.type == ActivityType.streaming: # Started Streaming #print('started stream') await RoleHandler.addStream(client, after)
async def measure(self, client, message): p = DictionaryReader() service = discovery.build('commentanalyzer', 'v1alpha1', developerKey=Key().perspectiveApiKey()) body = self.buildRequest(message.content, self.buildAttributes(self.defaultAttributes)) #print(json.dumps(body, indent=2)) response = service.comments().analyze(body=body).execute() #print(json.dumps(response, indent=2)) if response is not None: score = response['attributeScores']['TOXICITY']['summaryScore'][ 'value'] source = message.channel.name if isinstance( message.channel, TextChannel) else 'PM' if float(score) > 0.90: await client.get_channel( int(p.perspectiveLogChannelH2P()) ).send( 'Toxic Message Warning - {0:.2g}% Toxicity - on {2} from {1.author}({1.author.id})```{1.content}```' .format(score * 100.0, message, source))
async def generalMessage(message): p = DictionaryReader() try: roles = len(message.author.roles) except Exception: roles = 10 command = message.content[1::].split(' ')[0].lower() msg = p.commandReader(message.content[1::],message.channel.name) if msg != None: if command in p.whisperCommands(): if command == 'pub' and roles > 1 and 'help' not in message.content: await client.send_message(message.channel, msg) else: await client.send_message(message.author, msg) try: await client.delete_message(message) except (HTTPException, Forbidden): print('Error deleting message, probably from whisper') else: await client.send_message(message.channel, msg) else: msg = p.commandReader('invalid',message.channel.name) await client.send_message(message.author, msg) try: await client.delete_message(message) except (HTTPException, Forbidden): print('Error deleting message, probably from whisper')
async def newsSubscription(client, message): p = DictionaryReader() if not message.guild: return targetRole = '{0}News'.format(message.content[5::].capitalize()) print(targetRole) role = utils.find(lambda r: r.name == targetRole, message.author.guild.roles) # Role Desired doesn't exist if not role: await message.author.send( 'Invalid subscription name. Valid subscriptions are:\n{0}'. format(p.readEntry('validsubscriptions', ''))) else: # Doesn't have the role already if role not in message.author.roles: await message.author.add_roles( role, reason='Subscribed to {0}'.format(targetRole)) await message.author.send( p.readEntry('newssubscriptionadd', '').format(targetRole)) # Already has the role, unsubscribing else: await message.author.remove_roles( role, reason='Unsubscribed to {0}'.format(targetRole)) await message.author.send( p.readEntry('newssubscriptionremove', '').format(targetRole))
async def adminControl(message): p = DictionaryReader() roles = message.author.roles canBan = False for role in roles: canBan = canBan or (role.name in p.roles()) if not canBan: print('{0.author.name} can\'t manage members!'.format(message)) await message.author.send('You can\'t manage members!') return else: # Bans - Format: !ban 9999999999999 if message.content.startswith(prefix+'ban'): if not message.guild.me.guild_permissions.ban_members: await message.author.send('The bot does not have permissions to manage members.') return id = message.content.split(' ')[1] reason = ' '.join(message.content.split(' ')[2::]) try: user = await client.get_user_info(id) await message.guild.ban(user=user, reason=reason) if user != None: await message.author.send('User {0.mention} banned successfully'.format(user)) else: await message.author.send('Invalid user ID') except discord.HTTPException: pass finally: await message.delete() # Ban info - Format: !info 9999999999999 if message.content.startswith(prefix+'info'): if not message.guild.me.guild_permissions.view_audit_log: await message.author.send('The bot does not have permissions to view audit logs.') return id = message.content.split(' ')[1] isUserBanned = False try: await message.delete() except (HTTPException, Forbidden): print('Error deleting message, probably from whisper') user = await client.get_user_info(id) await message.author.send( 'User {0.mention}\n```Bans```'.format(user) ) async for entry in message.guild.audit_logs(action=discord.AuditLogAction.ban): if str(entry.target.id) == str(id): await message.author.send('-> User {0.target}({0.target.id}) was **banned** by {0.user}({0.user.id}) on {0.created_at} (UTC)\n\tReason: {0.reason}\n'.format(entry)) isUserBanned = True await message.author.send( '```Unbans```' ) async for entry in message.guild.audit_logs(action=discord.AuditLogAction.unban): if entry.target.id == int(id): await message.author.send('-> User {0.target} was **unbanned** by {0.user}({0.user.id}) on {0.created_at} (UTC)'.format(entry)) if not isUserBanned: await message.author.send('User was never banned.')
async def logAction(member, action): r = DictionaryReader() if member.server: await client.send_message( client.get_channel(r.actionLogChannel()), '[' + time.strftime("%Y-%m-%d %H:%M:%S") + '] {0.server.name} - {0.name} ({0.id}) {1}'.format(member, action)) else: await client.send_message( client.get_channel(r.actionLogChannel()), 'No Server - {0.name} ({0.id}) {1}'.format(member, action))
async def maintenanceMessages(message): if message.content.startswith(prefix+'update'): call(["git","pull"]) p = DictionaryReader() if message.content.startswith(prefix+'fullupdate'): if message.author.id not in p.admins(): await client.send_message(message.channel, 'You\'re not my dad, {0.mention}!'.format(message.author)) return call(["git","pull"]) call(["start_bot.sh"]) sys.exit()
async def on_message(message): r = DictionaryReader() # we do not want the bot to reply to itself if message.author == client.user: return if message.content.startswith(prefix): await messageHandler(message) if message.channel.name != None and message.channel.name in r.logChannels(): logger.log(message)
async def addStream(client, member): p = DictionaryReader() channel = client.get_channel(int(p.streamingBroadcastChannel())) currentlyStreaming = utils.find( lambda r: r.name == p.currentlyStreamingRole(), member.guild.roles) await RoleHandler.removeStream(client, member) stream = None for act in member.activities: if act.type == ActivityType.streaming: stream = act if channel is None: print('Streaming Channel not found!') return #if not await TwitchHandler.validateStream(stream.url, Key().twitchApiKey()): # return if not stream.game.startswith('World of Warcraft'): return title, description, avatar, views, followers = await TwitchHandler.fetchStreamInfo( stream.url, Key().twitchApiKey()) emb = Embed() emb.title = title emb.type = 'rich' emb.description = description emb.url = stream.url emb.colour = Colour.purple() emb.set_footer(text='Created by PriestBot', icon_url=p.h2pIcon()) emb.set_thumbnail(url=avatar) emb.set_author(name=member.name, icon_url=member.avatar_url) emb.add_field(name='Views', value=views) emb.add_field(name='Followers', value=followers) if currentlyStreaming not in member.roles: await member.add_roles(currentlyStreaming, reason='User started streaming') await channel.send( '{0.mention} is now Live on Twitch!'.format(member), embed=emb) else: # This could be slow, but shouldn't, assuming there should be few messages in the channel messages = await channel.history(limit=None).flatten() for message in messages: if member in message.mentions: await message.edit(embed=emb)
async def on_raw_reaction_add(payload): if payload.user_id == client.user.id: return r = DictionaryReader() print(r.readEntry('subscriptionchannel','')) print(payload.emoji.name) #Only for reactions inside the report channel if payload.channel_id == int(r.perspectiveLogChannel()): await toxicity.feedback(payload.emoji, payload.user_id, r) elif payload.channel_id == int(r.readEntry('subscriptionchannel','')): await RoleHandler.newsSubscriptionAdd(client, payload.emoji, payload.user_id, payload.guild_id)
async def on_message(message): r = DictionaryReader() if message.channel.id == int(r.perspectiveLogChannelH2P()): await toxicity.addReactions(r, message) # we do not want the bot to reply to itself if message.author == client.user: return if message.content.startswith(prefix): await messageHandler(message) if isinstance(message.channel, DMChannel) or message.channel.name in r.logChannels(): logger.log(message) await toxicity.measure(client, message)
async def logEdit(before, after): r = DictionaryReader() emb = Embed() emb.title = 'Message Edited in {0.channel.name}'.format(before) emb.type = 'rich' emb.url = after.jump_url emb.colour = Colour.blue() emb.set_footer(text='UserID: {0.author.id}'.format(before), icon_url=before.author.avatar_url) emb.set_author(name=before.author.name, icon_url=before.author.avatar_url) emb.add_field(name='Before', value=before.content) emb.add_field(name='After', value=after.content, inline=False) logChannel = client.get_channel(int(r.moderationLogChannel())) await logChannel.send(embed=emb)
async def removeStream(client, member): p = DictionaryReader() channel = client.get_channel(int(p.streamingBroadcastChannel())) currentlyStreaming = utils.find( lambda r: r.name == p.currentlyStreamingRole(), member.guild.roles) if channel is None: print('Streaming Channel not found!') return await member.remove_roles(currentlyStreaming, reason='User stopped streaming') # This could be slow, but shouldn't, assuming there should be few messages in the channel messages = await channel.history(limit=None).flatten() for message in messages: if member in message.mentions: await message.delete()
async def toggleUserState(client, before, after): p = DictionaryReader() streamingRole = utils.find(lambda r: r.name == p.streamingRole(), before.guild.roles) # User doesn't have the streaming role, move along if streamingRole not in before.roles: return # Left the server if after is None: await RoleHandler.removeStream(client, before) # Role was removed elif streamingRole in before.roles and streamingRole not in after.roles: print('role removed') await RoleHandler.removeStream(client, before) # Checks if the Game state changed or if the user isn't streaming # This or statement might be costly and subject to improvement elif before.activity != after.activity or after.activity is None or after.activity.type != ActivityType.streaming: # Fetches streaming activities in after and before to compare, to avoid reposting beforeStream = None stream = None for act in after.activities: if act.type == ActivityType.streaming: stream = act break for act in before.activities: if act.type == ActivityType.streaming: beforeStream = act break if after.activity is None or not stream: # Stopped Streaming await RoleHandler.removeStream(client, after) elif stream and beforeStream != stream: # Started Streaming await RoleHandler.addStream(client, after)
async def forwardMessage(message): p = DictionaryReader() roles = message.author.roles canSend = False for role in roles: canSend = canSend or (role.name in p.roles()) if not canSend: print('{0.author.name} can\'t send whispers'.format(message)) return entries = message.content.split(' ') target = message.mentions[0] if target != None: entry = ' '.join(entries[2::]) msg = p.commandReader(entry) if msg != None: await target.send(msg) await message.delete() await message.author.send('Message sent to {0.mention}'.format(target)) else: await message.channel.send('Invalid Message, {0.mention}'.format(message.author))
async def newsSubscriptionRemove(client, emoji, user_id, guild_id): if not emoji.is_custom_emoji(): return targetRole = '{0}News'.format(emoji.name.capitalize()) print(targetRole) guild = client.get_guild(guild_id) role = utils.find(lambda r: r.name == targetRole, guild.roles) if not role: return member = guild.get_member(user_id) p = DictionaryReader() if role in member.roles: await member.remove_roles( role, reason='Unsubscribed to {0}'.format(targetRole)) await member.send( p.readEntry('newssubscriptionremove', '').format(targetRole))
async def logDelete(message): r = DictionaryReader() logChannel = client.get_channel(int(r.moderationLogChannel())) if not message.guild: return deletedBy = message.author # Checks if the bot can see the audit log if message.guild.me.guild_permissions.view_audit_log: auditLogs = message.guild.audit_logs( limit=100, action=discord.AuditLogAction.message_delete) logs = await auditLogs.flatten() deletionLog = None for log in logs: if log.target.id == message.author.id: deletionLog = log break deletedBy = deletionLog.user if deletionLog else deletedBy emb = Embed() emb.title = 'Message Deleted in {0.channel.name}'.format(message) emb.type = 'rich' emb.url = message.jump_url emb.colour = Colour.red() emb.set_footer(text='Timestamp: ' + time.strftime("%Y-%m-%d %H:%M:%S")) emb.set_author(name=message.author.name, icon_url=message.author.avatar_url) emb.add_field(name='Author', value=message.author.name) emb.add_field(name='Deleted by', value=deletedBy.name) if not message.guild.me.guild_permissions.view_audit_log: emb.add_field(name='Warning', value='Bot cant see AuditLog') emb.add_field(name='Message', value=message.content, inline=False) await logChannel.send(embed=emb)
async def logBan(guild, user): r = DictionaryReader() logChannel = client.get_channel(int(r.moderationLogChannel())) if not guild: return bannedBy = guild.me banReason = '' # Checks if the bot can see the audit log if guild.me.guild_permissions.view_audit_log: auditLogs = guild.audit_logs(limit=100, action=discord.AuditLogAction.ban) logs = await auditLogs.flatten() banLog = None for log in logs: if log.target.id == user.id: banLog = log break bannedBy = banLog.user if banLog else bannedBy banReason = banLog.reason emb = Embed() emb.title = 'User {0.name} Banned'.format(user) emb.type = 'rich' emb.colour = Colour.dark_red() emb.set_footer(text='Timestamp: ' + time.strftime("%Y-%m-%d %H:%M:%S")) emb.set_author(name=user.name, icon_url=user.avatar_url) emb.add_field(name='Banned by', value=bannedBy.name) if not guild.me.guild_permissions.view_audit_log: emb.add_field(name='Warning', value='Bot cant see AuditLog') emb.add_field(name='Reason', value=banReason, inline=False) await logChannel.send(embed=emb)
async def generalMessage(message): p = DictionaryReader() try: roles = len(message.author.roles) except Exception: roles = 10 command = message.content[1::].split(' ')[0].lower() msg = '' if not isinstance(message.channel, DMChannel): msg = p.commandReader(message.content[1::],message.channel.name) else: msg = p.commandReader(message.content[1::],'PM') if msg != None: if command in p.whisperCommands(): if command == 'pub' and roles > 1 and 'help' not in message.content: await message.channel.send(msg) else: await message.author.send(msg) try: await message.delete() except (HTTPException, Forbidden): print('Error deleting message, probably from whisper') else: await message.channel.send(msg) else: if not isinstance(message.channel, DMChannel): msg = p.commandReader(message.content[1::],message.channel.name) else: msg = p.commandReader(message.content[1::],'PM') print(message.content[1::]) print(msg) await message.author.send(msg) try: await message.delete() except (HTTPException, Forbidden): print('Error deleting message, probably from whisper')
async def toggleStream(client, message): p = DictionaryReader() print(message.content) target = message.mentions[0] if message.mentions else message.author role = utils.find(lambda r: r.name == p.streamingRole(), target.roles) staff = utils.find(lambda r: r.name == p.roles(), message.author.roles) donor = utils.find(lambda r: r.name == p.donor(), message.author.roles) streamingRole = utils.find(lambda r: r.name == p.streamingRole(), message.author.guild.roles) # Target doesn't have the Streaming Role if role is None: # If user has the Staff role if staff is not None: await target.add_roles(streamingRole, reason='Role added by {0.name}'.format( message.author)) else: # Donors can add the role to themselves if donor is not None: await message.author.add_roles( streamingRole, reason='Donor adding role to themselves') # User already has the Streaming Role, so remove it else: # If user has the Staff role or is the author if staff is not None or target == message.author: await target.remove_roles( role, reason='Role removed by {0.name}'.format(message.author))
async def adminControl(message): p = DictionaryReader() roles = message.author.roles canBan = False for role in roles: canBan = canBan or (role.name in p.roles()) if not canBan: print('{0.author.name} can\'t manage members!'.format(message)) await message.author.send('You can\'t manage members!') return else: # Mass bans - Format: !banall id0 id1 id2 if message.content.startswith(prefix + 'banall'): if not message.guild.me.guild_permissions.ban_members: await message.author.send( 'The bot does not have permissions to manage members.') return ids = message.content.split(' ')[1::] reason = 'mass ban' bannedCount = 0 for id in ids: try: user = await client.fetch_user(id) await message.guild.ban(user=user, reason=reason, delete_message_days=7) if user != None: await message.author.send( 'User {0.mention} banned successfully'.format(user) ) bannedCount += 1 else: await message.author.send( '{0} is an invalid user ID'.format(str(id))) except discord.HTTPException: continue await message.author.send('Successfully banned {0} users'.format( str(bannedCount))) await message.delete() # Bans - Format: !ban 9999999999999 elif message.content.startswith(prefix + 'ban'): if not message.guild.me.guild_permissions.ban_members: await message.author.send( 'The bot does not have permissions to manage members.') return splitMessage = message.content.split(' ') id = splitMessage[1] deleteDays = 0 reasonStart = 2 if len(splitMessage) > 2: deleteDays = splitMessage[2] if splitMessage[2].isdigit( ) else 0 reasonStart = 3 if splitMessage[2].isdigit() else 2 reason = ' '.join(splitMessage[reasonStart::]) print(reason) try: user = await client.fetch_user(id) if user != None: await message.guild.ban(user=user, reason=reason, delete_message_days=deleteDays) await message.author.send( 'User {0.mention} banned successfully'.format(user)) else: await message.author.send('Invalid user ID') except discord.HTTPException: pass finally: await message.delete() # Ban info - Format: !info 9999999999999 elif message.content.startswith(prefix + 'info'): if not message.guild.me.guild_permissions.view_audit_log: await message.author.send( 'The bot does not have permissions to view audit logs.') return id = message.content.split(' ')[1] isUserBanned = False try: await message.delete() except (HTTPException, Forbidden): print('Error deleting message, probably from whisper') user = await client.fetch_user(id) await message.author.send( 'User {0.mention}\n```Bans```'.format(user)) async for entry in message.guild.audit_logs( action=discord.AuditLogAction.ban): if str(entry.target.id) == str(id): await message.author.send( '-> User {0.target}({0.target.id}) was **banned** by {0.user}({0.user.id}) on {0.created_at} (UTC)\n\tReason: {0.reason}\n' .format(entry)) isUserBanned = True await message.author.send('```Unbans```') async for entry in message.guild.audit_logs( action=discord.AuditLogAction.unban): if entry.target.id == int(id): await message.author.send( '-> User {0.target} was **unbanned** by {0.user}({0.user.id}) on {0.created_at} (UTC)' .format(entry)) if not isUserBanned: await message.author.send('User was never banned.')
async def sendWelcomeMessage(member): p = DictionaryReader() msg = p.commandReader('help') await client.send_message(member, msg)
async def itemMessage(message): p = DictionaryReader() msg = p.itemReader(message.content[1::]) await message.channel.send(msg)
async def sendWelcomeMessage(member): p = DictionaryReader() msg = p.commandReader('help') await member.send(msg)