async def _enable(self, ctx, role: discord.Role = None): exists = dbinteraction.dbexec( "SELECT server_id from serverdata WHERE server_id = ?", (ctx.guild.id, )) print(f"status, role : enabled {role.id}") try: if role == None: await ctx.send("No role provided") else: if exists != None: dbinteraction.dbexec( "UPDATE serverdata SET role = ? WHERE server_id = ?", (role.id, ctx.guild.id), ) else: dbinteraction.dbexec( "INSERT INTO serverdata VALUES(?,?, ?)", (ctx.guild.id, role.id, 0), ) em = discord.Embed(title="", color=discord.Color(0x32FF00)) em.add_field(name="Autorole enabled", value=f"Current role: {(role.mention)}") await ctx.send(embed=em) except (Exception) as e: print(e)
async def osulink(self, ctx, user=""): """Links the given osu username to your Konata account""" try: a = dbinteraction.dbexec("SELECT osuname FROM users WHERE id = ?", (ctx.message.author.id, )) if a != None: t = (user, ) ch = ctx.message.author dbinteraction.dbexec( "UPDATE users SET osuname = ? WHERE id = ? ", ( user, ctx.message.author.id, ), f=False) await ctx.send("Changed your Osu!username to {}".format(user)) else: ch = ctx.message.author dbinteraction.dbexec("INSERT INTO users values(?,?,?)", ( ctx.message.author.id, ch - ch[3:], user, ), f=False) except: print("err")
async def changegame(self, ctx): try: ard=random.randint(1,8) stt =dbinteraction.dbexec("SELECT status FROM playstat WHERE ID = ?", (ard,)) typ= dbinteraction.dbexec("SELECT type FROM playstat WHERE ID = ?", (ard,)) await self.bot.change_presence(activity=discord.Activity(type=typ, name=stt, url='https://twitch.tv/newe1337', details="skrrt skrrt")) except(IndexError): pass await ctx.send(":ok_hand:") await ctx.send("Now playing **{0}**".format(self.bot.discord.Game.name))
def update(self): print(self.guildc, self.userc, self.autorolec, self.commandsc) dbexec( "INSERT INTO stats1 VALUES(DATETIME('now','localtime'),?,?,?,?)", ( self.guildc, self.userc, self.autorolec, self.commandsc, ), db="stats")
async def _disable(self, ctx): exists = dbinteraction.dbexec("SELECT role from serverdata WHERE server_id = ?", (ctx.guild.id,)) print('disab') if(exists!=None): try: dbinteraction.dbexec("DELETE FROM serverdata WHERE server_id = ?", (ctx.guild.id,)) await ctx.send("Autorole disabled") except(Exception) as e: print(e) else: await ctx.send("Autorole wasn't enabled for this guild.")
async def roleswitch(self, ctx, bool: str): a=None if(bool=="on" or bool=="enable"): a=1 await ctx.send("Custom selfmade roles enabled") elif(bool=="off" or bool=="disable"): a=0 await ctx.send("Custom selfmade roles disabled") if a!=None: dbinteraction.dbexec("UPDATE serverdata SET usrmaderole=? WHERE server_id=,", (a, ctx.guild.id,))
def __init__(self): self.guildc = None self.userc = None self.autorolec = None self.commandsc = None self.datadogOpts = { "api_key": dbexec("dsaApiKey", log=True), "app_key": dbexec("ddAppKey", log=True), "statsd_host": "127.0.0.1", "statsd_port": 8125 } initialize(**self.datadogOpts)
async def osu(self, ctx, user=None, raw=False): """Returns Osu! stats for a given user.""" if user==None: try: a=dbinteraction.dbexec("SELECT osuname FROM users WHERE id = ?", (ctx.message.author.id,)) if a!=None: user=a else: return except(Exception) as e: await ctx.send("An error occured") print(e) return try: response = requests.get(f"https://osu.ppy.sh/api/get_user?k={self.k}&u={user}&mode=0&type=string") rj = response.json()[0] if(raw): await ctx.send(f"**RAW JSON DATA**\n```json\nrj}```") else: em = discord.Embed(title=f"Osu profile for {rj["username"]}", color=discord.Color(0xFD00FD)) em.set_thumbnail(url=f"https://a.ppy.sh/{rj["user_id"]}") em.add_field(name="Level", value=round(float(rj["level"]), 0)) em.add_field(name="Country", value=rj["country"]) em.add_field(name="PP", value=round(float(rj["pp_raw"]), 0)) em.add_field(name="Rank", value=f"#{rj["pp_rank"]}") em.add_field(name="Accuracy", value=f"{round(float(rj["accuracy"]), 2)}%") em.add_field(name="Play count", value=rj["playcount"]) em.add_field(name="SS ranks", value=rj["count_rank_ss"]) em.add_field(name="S ranks", value=rj["count_rank_s"]) em.add_field(name="A ranks", value=rj["count_rank_a"]) em.set_footer(text=f"Requested by {ctx.message.author}") await ctx.send(embed=em) except: await ctx.send("The provided user could not be found.")
async def _disablecustom(self, ctx): exists = dbinteraction.dbexec( "SELECT usrmaderole from serverdata WHERE server_id = ?", (ctx.guild.id, )) print("disab") if exists != 0: try: dbinteraction.dbexec( "UPDATE serverdata SET usrmaderole = 0 WHERE server_id = ?", (ctx.guild.id, ), ) await ctx.send("Autorole disabled") except (Exception) as e: print(e) else: await ctx.send("Autorole wasn't enabled for this guild.")
async def colorole(self, ctx, color: str): couleur = colrs.RGB(color) print("color : {}".format(color)) if(dbinteraction.dbexec('SELECT usrmaderole FROM serverdata WHERE server_id=?', (ctx.guild.id,))): if(couleur): await ctx.guild.create_role(name=ctx.message.author.name, hoist=True, colour=discord.Color(couleur), reason="Usermade colored role") else: await ctx.send('invalid color')
async def on_guild_remove(guild): try: payload = { "embeds": [{ "title": "Nouveau serveur", "color": 16711684, "footer": { "icon_url": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/3f/3fabd870d12b4301114bd6ffe9267b8eb560036d_full.jpg", "text": "Total: {} serveurs".format(len(bot.guilds)) }, "thumbnail": { "url": guild.icon }, "fields": [{ "name": "Nom", "value": guild.name, "inline": True }, { "name": "Membres", "value": len(guild.members), "inline": True }, { "name": "ID", "value": guild.id, "inline": False }] }] } headers = {'Content-Type': 'application/json'} response = requests.post(dbinteraction.dbexec("serverhook", log=True), data=json.dumps(payload), headers=headers) return response except: print('guild leave, ms fail') call([ "curl", "--data", "content=Nom: *{}*\nID : `{}`\n Total: {} serveurs&username=Serveur quitté&avatar_url=https://cdn.discordapp.com/attachments/440454225961680896/440454482657017856/goodjob.gif" .format(guild.name, guild.id, len(bot.guilds)), dbinteraction.dbexec("serverhook", log=True) ])
def stats(): global commandcnt print("Stats INIT") print("dog OK") dog.gather(len(bot.guilds), len(bot.users), dbinteraction.dbexec("SELECT COUNT(*) FROM serverdata"), commandcnt) dog.update() print("Dog done") commandcnt = 0
async def autorole(self, ctx): print(ctx.invoked_subcommand) exists = dbinteraction.dbexec("SELECT role from serverdata WHERE server_id = ?", (ctx.guild.id,)) em = None if (exists == None): em = discord.Embed(title="Autorole is disabled for this guild.", color=discord.Color(0xff0000)) else: em = discord.Embed(title="Autorole is enabled for this guild.", color = discord.Color(0x32ff00)) rol = discord.utils.get(ctx.guild.roles, id=exists) em.add_field(name="Current role:", value=rol.mention) await ctx.send(embed=em)
async def on_command(ctx): global commandcnt commandcnt += 1 print( f"{bcolors.WARNING} [COMMAND] | {ctx.message.author} : {ctx.message.clean_content[2:]} [{commandcnt}] {bcolors.ENDC}" ) call([ "curl", "--data", "content=**__{}__** : `{}`&username=Commande exécutée&avatar_url=https://cdn.discordapp.com/attachments/440454225961680896/440454482657017856/goodjob.gif" .format(ctx.message.author, ctx.message.clean_content[2:]), dbinteraction.dbexec("comhook", log=True) ])
async def _enablecustom(self, ctx, role: discord.Role = None): exists = dbinteraction.dbexec( "SELECT usrmaderole from serverdata WHERE server_id = ?", (ctx.guild.id, )) try: if exists != None: dbinteraction.dbexec( "UPDATE serverdata SET usrmaderole = 1 WHERE server_id = ?", (ctx.guild.id, ), ) else: dbinteraction.dbexec("INSERT INTO serverdata VALUES(?,?,?)", ( ctx.guild.id, None, 1, )) em = discord.Embed(title="Custom roles are enabled", color=discord.Color(0x32FF00)) await ctx.send(embed=em) except (Exception) as e: print(e)
def triggerAlarm(self, args, stop=False, ext=False): if not self.triggered or stop: #Empêchement des doublons try: data = None if stop: self.logger.debug('Alarme arretée') data = {'status': 0, 'trigTime': None, 'id': 1} loop.stop() #Arrêt de la loop else: self.logger.critical('ALARME DECLENCHEE') asyncio.ensure_future( subprocess.run([ "aplay", "/home/pi/projet/alarm.wav" ])) #Ajout de la lecture du son à la loop loop.run_forever() #Démarage de la loop try: a = [] mailList = dbexec( "SELECT lemail FROM comptes WHERE sendmail = 1", mult=True, db="/home/pi/projet/db/store.db") for i in mailList: a.append(i[0]) self.sendMail(a, args) except: self.logger.warning("Impossible d'envoyer les mails") data = { 'status': 1, 'trigTime': str(datetime.now()), 'id': 1 } self.triggered = True if not ext: try: requests.post("http://127.0.0.1:8080/api/alarm", json=data) except requests.HTTPError: self.logger.error('HTTP err') except (Exception) as e: self.logger.error(e)
async def customrole(self, ctx, roleName: str = None, color: str = None): """Creates a custom role, if enabled Parameters ------------ name: str The role's name. Use quotes if there are spaces color: str Color name, RGB values as "r,g,b", hex value """ exists = dbinteraction.dbexec( "SELECT usrmaderole from serverdata WHERE server_id = ?", (ctx.guild.id, )) em = None if not exists: await ctx.send(embed=discord.Embed( title="Custom roles are disabled for this guild.", color=discord.Color(0xFF0000), )) else: if not roleName and exists: em = discord.Embed( title="Custom roles are enabled for this guild.", color=discord.Color(0xFF0000), ) else: rid = dbinteraction.dbexec( "SELECT role FROM userCustomRole WHERE guildId = ? AND userID = ?", ( ctx.guild.id, ctx.author.id, ), ) if rid: r = get(ctx.guild.roles, id=int(rid)) await ctx.author.remove_roles(r) r.delete(reason="[KONA] Custom role replacement") role = await ctx.guild.create_role( name=roleName, permissions=discord.Permissions.none(), color=discord.Color(int(colorlib(color).hex_l[1:], 16)) if color else discord.Color.default() if color else discord.Color.default(), hoist=True, mentionable=True, reason="[KONA] Custom role", ) if rid: dbinteraction.dbexec( "UPDATE userCustomRole SET role = ? WHERE guildId = ? AND userID = ?", ( role.id, ctx.guild.id, ctx.author.id, )) else: dbinteraction.dbexec( "INSERT into userCustomRole values(?,?,?)", ( ctx.guild.id, ctx.author.id, role.id, )) em = discord.Embed( title=f"You have been given the {roleName} role.", color=discord.Color.green(), ) await ctx.author.add_roles(role, reason="[KONA] Custom role") await ctx.send(embed=em)
async def on_member_join(member): a = dbinteraction.dbexec("SELECT role FROM serverdata WHERE server_id = ?", (member.guild.id, )) if a != None: role = discord.utils.get(member.guild.roles, id=a) await member.add_roles(role, reason="[KONA] Autorole")
async def on_guild_join(guild): try: em = discord.Embed(title="Hello ໒( ●ᴥ ●)ʋ", color=discord.Color(0xff0000)) em.set_thumbnail( url= "https://cdn.discordapp.com/avatars/366632492590956544/e33fb154663f5a63138d934224b47c7d.png?size=1024" ) em.add_field(name="The name's Konata", value="A capable and experimental discord bot!\n\ To see the list of my commands, type **__n$__help** <:NWKonataThumbsUp:445210207597887489>\n\ If you like what i do, please consider [voting for this bot](https://discordbots.org/bot/366632492590956544) and suggest this bot around, it would help me a lot, thanks (\*´▽`\*)!" ) ch = guild.system_channel print("channel set: {}".format(ch)) if not ch: print("not ch") for c in guild.text_channels: if not c.permissions_for(guild.me).send_messages: print("ch test") continue ch = c print("ch found") break print("done") await ch.send(embed=em) try: payload = { "embeds": [{ "title": "Nouveau serveur", "color": 11468544, "footer": { "icon_url": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/3f/3fabd870d12b4301114bd6ffe9267b8eb560036d_full.jpg", "text": "Total: {} serveurs".format(len(bot.guilds)) }, "thumbnail": { "url": guild.icon }, "fields": [{ "name": "Nom", "value": guild.name, "inline": True }, { "name": "Membres", "value": len(guild.members), "inline": True }, { "name": "ID", "value": guild.id, "inline": False }] }] } headers = {'Content-Type': 'application/json'} response = requests.post(dbinteraction.dbexec("serverhook", log=True), data=json.dumps(payload), headers=headers) return response except (Exception) as e: print(e) call([ "curl", "--data", "content=Nom: *{}*\nID : `{}`\n Total: {} serveurs&username=Nouveau serveur&avatar_url=https://cdn.discordapp.com/attachments/440454225961680896/440454482657017856/goodjob.gif" .format(guild.name, guild.id, len(bot.guilds)), dbinteraction.dbexec("serverhook", log=True) ]) except (Exception) as e: print(e)
@bot.command(aliases=["rl"], hidden=True) @commands.is_owner() async def reload(ctx, extension_name: str): try: bot.unload_extension(extension_name) bot.load_extension(extension_name) except (AttributeError, ImportError) as e: await ctx.message.add_reaction('🈲') await ctx.send("```py\n{}: {}\n```".format(type(e).__name__, str(e))) return await ctx.message.add_reaction('🉑') initial_extensions = [ 'simple', "admin", "osu", "audio", "anime", "owner", "dbotsapi", "servmgmt", "audio2" ] if __name__ == "__main__": for extension in initial_extensions: try: bot.load_extension(extension) except Exception as e: exc = '{}: {}'.format(type(e).__name__, e) print('Failed to load extension `{}\n{}`'.format(extension, exc)) print('{}Successfully logged in and booted...!{}'.format( bcolors.OKGREEN, bcolors.ENDC)) bot.run(dbinteraction.dbexec('dstk', log=True), reconnect=True)
def __init__(self,bot): self.bot = bot self.k = dbinteraction.dbexec("osuKey", log=True)