async def destroygroup(message): outputstr = "Admin command invoked by {}".format(message.author.name) await message.channel.send(outputstr) writeToFile(filename, outputstr) if len(groupList) == 0: outputstr = "There are no active groups!" await message.channel.send(outputstr) writeToFile(filename, outputstr) elif not any(map(str.isdigit, message.content.lower())): await message.channel.send( "Usage: !destroygroup <group number>.\nPlease take a look at !whoisgrouped for the group number" ) writeToFile( filename, "{} invoked command without numbers".format(message.author.name)) else: groupNo = int(message.content.lower().split(' ')[1]) - 1 if groupNo < 0 or groupNo >= len(groupList): await message.channel.send("Invalid group number") writeToFile( filename, "{} invoked command with incorrect number".format( message.author.name)) return ungroupList = [k for k, v in allgrouped.items() if int(v) == groupNo] try: for i in ungroupList: await ungroup(message, i) except KeyError as e: writeToFile(filename, "Error: {}".format(e))
async def on_member_join(self, member): welcomechannel = self.__client.get_channel(self.__channels['welcome']) if welcomechannel is not None: message = await welcomechannel.send(f'Welcome, {member.mention}. React to this message with a ✅ to accept the rules') await message.add_reaction('✅') def check(reaction, user): return str(reaction.emoji) == '✅' and user == member try: # 30 Day timeout user = (await self.__client.wait_for('reaction_add', timeout=2592000, check=check))[1] await message.remove_reaction('✅', user) await message.delete() except asyncio.TimeoutError: await self.log(f"Welcome message {message.id} to {member.name} is not being tracked anymore, please ask them to rejoin or manually add Friend role") await message.delete() return except NotFound: writeToFile(self.__filename, "Error, message not found") pass role = get(self.__client.guilds[0].roles, id=self.__roles['friend']) await user.add_roles(role) outputstr = "Gave the {} role to {}".format(role.name, user.name) await self.log(outputstr) writeToFile(self.__filename, outputstr)
async def register(self, message): c = self.__cursor person = message.author if len(message.mentions) > 0 and "admin" in [ y.name.lower() for y in message.author.roles ]: person = message.mentions[0] if "based" in [y.name.lower() for y in message.author.roles]: outputstr = "{} is already registered. Type `!sr @username` for more".format( person.name) await message.channel.send(outputstr) writeToFile(self.__filename, "[{}] ".format(message.author.name) + outputstr) return query = "INSERT INTO {} (name) VALUES ('{}')".format( self.__sr_table_name, person.name) if not c.execute(query): outputstr = "There's been an error and it has been reported. Please try again, later" await message.channel.send(outputstr) outputstr = "Error in executing query {}".format(query) return outputstr = "Successfully added new database entry for {}\n".format( person.name) writeToFile(self.__filename, outputstr) outputstr += "Please set your SR using `!set <role> <sr>`\n" outputstr += "For more commands use `!sr --help`" await message.channel.send(outputstr)
async def on_ready(): print("Live") global dbservice global filename dbservice = await DBService.construct(filename) channelID = 800499934365220864 # welcome channel = client.get_channel(channelID) roleID = 800501133642170388 # friend role = get(client.guilds[0].roles, id=roleID) message = await channel.send( "React to this message with ✅ to accept the rules and access the server" ) def check(reaction, user): return str(reaction.emoji) == '✅' and user != message.author while True: await message.add_reaction('✅') user = (await client.wait_for('reaction_add', check=check))[1] try: await message.remove_reaction('✅', user) except NotFound: writeToFile(filename, "Error, message not found") _thread = threading.Thread(target=remove_reaction_sync, args=(message, user)) _thread.start finally: await user.add_roles(role) outputstr = "Gave the {} role to {}".format(role.name, user.name) writeToFile(filename, outputstr)
async def bug(message): global numBugs myID = '<@!317936860393635843>' await message.channel.send( "Bug Reported, thank you.\n Ping {} for updates".format(myID)) outputstr = "---------------------------------------BUG REPORTED--------------------------------------------" writeToFile(filename, outputstr) numBugs += 1
async def log(self, outputstr): logchannel = self.__client.get_channel(self.__channels['log']) if logchannel is not None: await logchannel.send(outputstr) else: writeToFile(self.__filename, "Error: Could not find log channel") print("Could not find log channel") writeToFile(self.__filename, outputstr)
async def smurf(message): if len(message.mentions) > 0 and "admin" in [ y.name.lower() for y in message.author.roles ]: user = message.mentions[0] else: user = message.author smurfList.append(user) if user not in [*globalMap]: await on(message) outputstr = "{} is now smurfing".format(user.name) await message.channel.send(outputstr) writeToFile(filename, outputstr)
async def lmk(message): notifier = "All" if len(message.mentions) > 0: notifier = message.mentions[0] if notifier in notifyDict.keys(): notifyDict[notifier].append(message.author) else: notifyDict[notifier] = [message.author] outputstr = "{} will be notified the next time {} goes on".format( message.author.name, notifier.name if len(message.mentions) > 0 else "someone") writeToFile(filename, outputstr) await message.channel.send(outputstr)
def get_sender_timezone(self, author_id): c = self.__cursor query = "SELECT timezone FROM {} WHERE id = '{}'".format( self.__tz_table_name, author_id) if not c.execute(query): print("Error executing query") return timezone = c.fetchall() if len(timezone) == 0: outputstr = "Can't find any details for {}".format(author_id) writeToFile(self.__filename, outputstr) return return timezone[0][0]
async def on(message): addedPerson = message.author mentions = message.mentions if len(mentions) > 0: if "admin" in [y.name.lower() for y in message.author.roles]: outputstr = "Admin command invoked by {}".format( message.author.name) await message.channel.send(outputstr) writeToFile(filename, outputstr) for i in mentions: globalMap[i] = datetime.datetime.now() outputstr = "{} is now online!".format(i.name) await notify(message, i, outputstr) await message.channel.send(outputstr) writeToFile(filename, outputstr) else: outputstr = "Sorry, {}, you do not have admin privellages!, you cannot invoke off or on for other users".format( message.author.name) await message.channel.send(outputstr) writeToFile(filename, outputstr) return else: globalMap[addedPerson] = datetime.datetime.now() outputstr = "{} is now online!".format(message.author.name) await notify(message, addedPerson, outputstr) await message.channel.send(outputstr) writeToFile(filename, outputstr)
async def whoison(message): sortedList = sorted(globalMap.items(), key=lambda x: x[1]) end = datetime.datetime.now() if len(sortedList) == 0: outputstr = "No one is on at the moment, {}, if you're going online, say \"!on\" to let people know!".format( message.author.name) await message.channel.send(outputstr) writeToFile(filename, outputstr) return for i in sortedList: outputstr = "{}".format(i[0].name) if i[0] in smurfList: outputstr += " (smurf) " outputstr += " has been on for {}".format(str((end - i[1]))) await message.channel.send(outputstr.split('.')[0]) writeToFile(filename, outputstr)
async def parse_set_query(self, message): args = message.content.split(' ') try: role = args[-2] except IndexError: outputstr = "Usage: !set {@user} role <sr>" writeToFile(self.__filename, "[{}]".format(message.author.name) + outputstr) outputstr += "\nList of acceptable roles - 'tank', 'dps', 'damage', 'dmg', 'support', 'heals'" await message.channel.send(outputstr) return [] roleList = ['tank', 'dps', 'damage', 'dmg', 'support', 'heals'] if not role in roleList: outputstr = "Usage: !set {@user} role <sr>" writeToFile(self.__filename, "{}: ".format(message.author.name) + outputstr) outputstr += "\nList of acceptable roles - ['tank', 'dps', 'damage', 'dmg', 'support', 'heals']" await message.channel.send(outputstr) return [] try: if len(args[-1]) != 4: outputstr = "Please make sure the SR is a 4 digit number" await message.channel.send(outputstr) writeToFile(self.__filename, outputstr) return [] newSR = int(args[-1]) except ValueError: outputstr = "Please make sure the SR is correctly written as the last part of the message" writeToFile( self.__filename, "Invoked by {}: ".format(message.author.name) + outputstr) await message.channel.send(outputstr) return [] if newSR < 0: outputstr = "{}, please make sure the SR is a positive number".format( message.author.name) writeToFile(self.__filename, outputstr) await message.channel.send(outputstr) return [] return [newSR, role]
async def construct(cls, filename): self = DBService() self.__filename = filename conn = sqlite3.connect('overwatch_team.db') if conn == None: writeToFile(self.__filename, "Error connecting to database") return self.__cursor = conn.cursor() outputstr = "Successfully constructed DBService" print(outputstr) writeToFile(self.__filename, outputstr) self.__sr_table_name = "srdata" self.__tz_table_name = "tzinfo" return self
async def set(self, message): c = self.__cursor mentions = message.mentions if len(mentions) > 0: if "admin" in [y.name.lower() for y in message.author.roles]: user = mentions[0] else: outputstr = "Sorry, {}. You'll need admin permissions to do that".format( message.author.name) await message.channel.send(outputstr) writeToFile(self.__filename, outputstr) return else: user = message.author try: newSR, role = await self.parse_set_query(message) except ValueError: return person = user.name query = "SELECT * FROM {} WHERE name = '{}'".format( self.__sr_table_name, person) if not c.execute(query): outputstr = "There's been an error and it has been reported. Please try again, later" await message.channel.send(outputstr) outputstr = "Error in executing query {}".format(query) return user = c.fetchall() if len(user) == 0: outputstr = "Can't find any details for {}. If you're not registered, type `!register` to start!".format( person) writeToFile(self.__filename, outputstr) await message.channel.send(outputstr) return user = user[0] if role in ('dps', 'dmg'): role = "damage" elif role == "heals": role = "support" query = "UPDATE {} SET {} = {} WHERE name = '{}'".format( self.__sr_table_name, role, newSR, person) if not c.execute(query): outputstr = "There's been an error and it has been reported. Please try again, later" await message.channel.send(outputstr) outputstr = "Error in executing query {}".format(query) return outputstr = "Successfully changed {}'s {} SR to {}".format( person, role, newSR) await message.channel.send(outputstr) writeToFile(self.__filename, outputstr) await self.sr(message)
async def off(message): deletedPerson = message.author async def turnOff(user): try: del globalMap[user] # Remove from smurfs if user in smurfList: smurfList.remove(user) # Remove from groups if isGrouped(user.id): await ungroup(message, user) return "{} is now offline".format(user.name) except KeyError: return "{} was not online".format(user.name) mentions = message.mentions if len(mentions) > 0: if "admin" in [y.name.lower() for y in message.author.roles]: for i in mentions: outputstr = await turnOff(i) await message.channel.send(outputstr) writeToFile(filename, outputstr) else: outputstr = "Sorry, {}, you do not have admin privellages!, you cannot invoke off or on for other users".format( message.author.name) await message.channel.send(outputstr) writeToFile(filename, outputstr) else: outputstr = await turnOff(deletedPerson) await message.channel.send(outputstr) writeToFile(filename, outputstr)
async def on_message(self, message): if message.author == self.__client.user: return # Parse Time regex = r'\d{1,2}\s?(?:(?:am|pm)|(?::\d{1,2})\s?(?:am|pm)?)' time_matches = re.findall(regex, message.content.lower()) if len(time_matches) > 0: outputstr = await self.parse_time(time_matches, message.author.id) await message.channel.send(outputstr) # Help/Information if "!status" in message.content.lower(): if message.author.name == "Orisa": return duration = datetime.datetime.now() - self.__START outputstr = "The bot is online and has been running for {}\n".format( str(duration).split('.')[0]) if "-v" in message.content.lower(): outputstr += "In this session, \n" outputstr += "{} unique instructions have been processed\n".format( self.__numInstr + 1) # +1 for current instruction outputstr += "{} unique bugs have been reported\n".format( self.__numBugs) # Saving this space for any other meta information people might need await message.channel.send(outputstr) writeToFile(self.__filename, outputstr) if "!needhealing" in message.content.lower( ) or "!ineedhealing" in message.content.lower(): outputstr = "Hi, I'm Orisa, a bot made by Zoid to automate the boring stuff on this server. For a full list of commands and documentation follow the link below \n" outputstr += "https://bhavdeepsinghb.github.io/OrisaBot" await message.channel.send(outputstr) # Admin commands if "!destroygroup" in message.content.lower() and "team member" in [ y.name.lower() for y in message.author.roles ]: await self.__coreservice.destroygroup(message) if "!alloff" in message.content.lower() and "team member" in [ y.name.lower() for y in message.author.roles ]: await self.__coreservice.alloff(message) if "!practice" in message.content.lower() and "team member" in [ y.name.lower() for y in message.author.roles ]: globalMap = await self.__coreservice.get_online_users() await practice(message, globalMap, self.__client) # General User Commands # Core Service if "!on" in message.content.lower(): await self.__coreservice.on(message) if "!smurf" in message.content.lower(): await self.__coreservice.smurf(message) if message.content.lower() in [ "!whoison", "!whoson", "!whoon", "!whothefuckison", "!whotfison" ]: await self.__coreservice.whoison(message) if "!off" in message.content.lower(): await self.__coreservice.off(message) if "!lmk" in message.content.lower(): await self.__coreservice.lmk(message) if "!group" in message.content.lower(): await self.__coreservice.group(message) if "!ungroup" in message.content.lower(): await self.__coreservice.ungroup_helper(message) if "!whoisgrouped" in message.content.lower(): await self.__coreservice.whoisgrouped(message) # Serviceless if "!bug" in message.content.lower(): myID = '<@!317936860393635843>' await message.channel.send( "Bug Reported, thank you.\n Ping {} for updates".format(myID)) outputstr = "---------------------------------------BUG REPORTED--------------------------------------------" writeToFile(self.__filename, outputstr) self.__numBugs += 1 # DB Service if "!sr" in message.content.lower(): if "team member" in [y.name.lower() for y in message.author.roles]: await self.__dbservice.sr(message) else: outputstr = "Sorry, {}. You'll have to be a team member to do that".format( message.author.name) await message.channel.send(outputstr) if "!set" in message.content.lower(): if "team member" in [y.name.lower() for y in message.author.roles]: await self.__dbservice.set(message) else: outputstr = "Sorry, {}. You'll have to be a team member to do that" if "!register" in message.content.lower(): if "team member" in [y.name.lower() for y in message.author.roles]: await self.__dbservice.register(message) else: outputstr = "Sorry, {}. You'll have to be a team member to do that" #Misc - won't be written to log files if message.content.lower() == "f": await message.channel.send("{} has put some respecc on it".format( message.author.name)) if message.content.lower() == "a": await message.channel.send("{} has assembled the Avengers!".format( message.author.name)) if message.content.lower() == "x": await message.channel.send("{} has assembled the X-Men!".format( message.author.name)) self.__numInstr += 1
async def sr(self, message): c = self.__cursor if "--help" in message.content.lower( ) or "-help" in message.content.lower(): await self.sr_help(message) return if "-team" in message.content.lower(): c.execute("SELECT * FROM {}".format(self.__sr_table_name)) highestList = [] everyone = c.fetchall() for i in everyone: high = 0 for j in i[2:]: if j is None: continue if int(j) > high: high = int(j) highestList.append(high) team_average = statistics.mean(highestList) median = statistics.median(highestList) standard_dev = statistics.stdev(highestList) outputstr = "**Team Average SR: {:.2f}**\n".format(team_average) if "-v" in message.content.lower(): outputstr += "Median (exact middle) SR: {:.2f}\n".format( median) outputstr += "Standard Deviation: {:.2f}\n".format( standard_dev) writeToFile(self.__filename, "[{}]".format(message.author.name) + outputstr) outputstr += "\nPlease note that this is based on the provided data so far. Type !sr --help for commands." await message.channel.send(outputstr) return person = message.author.name if len(message.mentions) > 0: person = message.mentions[0].name writeToFile( self.__filename, "[{}] invoked !sr for {}".format(message.author.name, person)) query = "SELECT * FROM {} WHERE name = '{}'".format( self.__sr_table_name, person) if not c.execute(query): outputstr = "There's been an error and it has been reported. Please try again, later" await message.channel.send(outputstr) outputstr = "Error in executing query {}".format(query) return user = c.fetchall() if len(user) == 0: outputstr = "No results found for {}, please register using `!register`".format( person) await message.channel.send(outputstr) writeToFile(self.__filename, outputstr) return user = user[0] high = 0 high_index = 0 for i in user[2:]: if i is not None and int(i) > high: high = int(i) high_index = user.index(i) outputstr = "For user **{}**\n".format(person) outputstr += "**Tank: {}**\n".format( user[2]) if high_index == 2 else "Tank: {}\n".format(user[2]) outputstr += "**Damage: {}**\n".format( user[3]) if high_index == 3 else "Damage: {}\n".format(user[3]) outputstr += "**Support: {}**\n".format( user[4]) if high_index == 4 else "Support: {}\n".format(user[4]) await message.channel.send(outputstr) writeToFile(self.__filename, outputstr)
async def group(message): blockedList = [] acceptedList = [] callerGroup = None mentions = message.mentions if len(mentions) == 0: await message.channel.send("Usage !group @<user> or [list of users]") writeToFile( filename, "{} used incorrect group creation syntax".format( message.author.name)) return elif message.author not in [*globalMap]: outputstr = "Group Creation Failure: {} is not online. Please type \"!on\" tp set your status as online".format( message.author.name) await message.channel.send(outputstr) writeToFile(filename, outputstr) return else: if isGrouped(message.author.id): callerGroup = allgrouped[message.author] else: newGroup = [message.author] groupList.append(newGroup) callerGroup = groupList.index(newGroup) allgrouped[message.author] = callerGroup if message.author in mentions: mentions.remove(message.author) for i in mentions: if i in [*allgrouped] or i not in [*globalMap]: blockedList.append(i.name) else: acceptedList.append(i.name) groupList[callerGroup].append(i) allgrouped[i] = callerGroup validateGroup(message) if message.author not in [*allgrouped]: writeToFile( filename, "{} created an invalid group, handled".format( message.author.name)) await message.channel.send( "Group invalid, number of valid members must be at least 2") else: outputstr = "New Group Created for {}!".format(message.author.name) await message.channel.send(outputstr) writeToFile(filename, outputstr) if len(acceptedList) > 0: outputstr = "The following players were added to the group {}".format( acceptedList).replace('[', '').replace(']', '') await message.channel.send(outputstr) writeToFile(filename, outputstr) if len(blockedList) > 0: outputstr = "The following players were not added since they are already grouped or offline, type !ungroup to remove yourself or !on to set your status as online {}".format( blockedList).replace('[', '').replace(']', '') await message.channel.send(outputstr) writeToFile(filename, outputstr)
async def on_message(message): global numInstr global numBugs global dbservice if message.author == client.user: return if "!on" in message.content.lower(): await on(message) if "!smurf" in message.content.lower(): await smurf(message) if message.content.lower() in [ "!whoison", "!whoson", "!whoon", "!whothefuckison", "!whotfison" ]: await whoison(message) if "!off" in message.content.lower(): await off(message) if "!lmk" in message.content.lower(): await lmk(message) #Admin commands if "!alloff" in message.content.lower() and "admin" in [ y.name.lower() for y in message.author.roles ]: globalMap.clear() allgrouped.clear() groupList.clear() outputstr = "Admin command invoked by {}, everyone is off! All groups destroyed!".format( message.author.name) await message.channel.send(outputstr) writeToFile(filename, outputstr) # Status Commands if "!status" in message.content.lower(): if message.author.name == "Orisa": return duration = datetime.datetime.now() - START outputstr = "The bot is online and has been running for {}\n".format( str(duration).split('.')[0]) if "-v" in message.content.lower(): outputstr += "In this session, \n" outputstr += "{} unique instructions have been processed\n".format( numInstr + 1) # +1 for current instruction outputstr += "{} unique bugs have been reported\n".format(numBugs) # Saving this space for any other meta information people might need await message.channel.send(outputstr) writeToFile(filename, outputstr) if "!needhealing" in message.content.lower( ) or "!ineedhealing" in message.content.lower(): outputstr = "Hi, I'm Orisa, a bot made by Zoid to automate the boring stuff on this server. For a full list of commands and documentation follow the link below \n" outputstr += "https://bhavdeepsinghb.github.io/OrisaBot" await message.channel.send(outputstr) # Grouping if "!group" in message.content.lower(): await group(message) if "!ungroup" in message.content.lower(): if message.author not in [*globalMap]: outputstr = "{} is not online, therefore not part of any groups".format( message.author.name) await message.channel.send(outputstr) writeToFile(filename, outputstr) elif message.author not in [*allgrouped]: outputstr = "{} was not part of a group".format( message.author.name) await message.channel.send(outputstr) writeToFile(filename, outputstr) else: await ungroup(message, message.author) if "!whoisgrouped" in message.content.lower(): if len(groupList) == 0: await message.channel.send( "There are no active groups, type !group @<user> or [a list of users] to start grouping up!" ) else: await message.channel.send("The following is a list of all groups") nickList = [] for i in groupList: nickList = [] for x in i: nickList.append(x.nick if x.nick is not None else x.name) await message.channel.send("{}) {}".format( groupList.index(i) + 1, nickList)) writeToFile( filename, "{} invoked whoisgrouped command. Returned {} results".format( message.author.name, len(groupList))) # Admin command for destroying groups if "!destroygroup" in message.content.lower() and "admin" in [ y.name.lower() for y in message.author.roles ]: await destroygroup(message) #Practice Command for admins, to avoid spam if "!practice" in message.content.lower() and "admin" in [ y.name.lower() for y in message.author.roles ]: await practice(message, globalMap, client) # Bug Command to report bugs, marked in the logfile + mentions user if "!bug" in message.content.lower(): await bug(message) if "!sr" in message.content.lower(): if "team member" in [y.name.lower() for y in message.author.roles]: await dbservice.sr(message) else: outputstr = "Sorry, {}. You'll have to be a team member to do that".format( message.author.name) await message.channel.send(outputstr) if "!set" in message.content.lower(): if "team member" in [y.name.lower() for y in message.author.roles]: await dbservice.set(message) else: outputstr = "Sorry, {}. You'll have to be a team member to do that" if "!register" in message.content.lower(): if "team member" in [y.name.lower() for y in message.author.roles]: await dbservice.register(message) else: outputstr = "Sorry, {}. You'll have to be a team member to do that" #Misc - won't be written to log files if message.content.lower() == "f": await message.channel.send("{} has put some respecc on it".format( message.author.name)) if message.content.lower() == "a": await message.channel.send("{} has assembled the Avengers!".format( message.author.name)) if message.content.lower() == "x": await message.channel.send("{} has assembled the X-Men!".format( message.author.name))