我们从Python开源项目中,提取了以下39个代码示例,用于说明如何使用discord.gg()。
def _list_channels(self, ctx): """Lists YouTube channels with announcements enabled""" guild = ctx.message.guild if guild.id in self.ids: try: data = discord.Embed( title="**__Announcement Channels__**\n", colour=discord.Colour(value=11735575)) k = self.ids[guild.id]['yt_channel'] data.add_field( name="YouTube Channel", value=k) data.add_field( name="Discord Channel", value=self.ids[guild.id]['channel']) data.set_footer( text="Made with \U00002665 by Francis#6565. Support server: https://discord.gg/yp8WpMh") await ctx.send(embed=data) except IndexError as e: logger.exception( "An error occured while pulling data from list... {}".format(e))
def on_guild_join(self, guild): """Send welcome message to the server owner""" message = ("Greetings! My name is **{}**, and my sole responsibility is to help you and " "your group kick ass in Destiny 2! You're receiving this message because you " "or one of your trusted associates has added me to **{}**.\n\n" "**Command Prefix**\n\n" "My default prefix is **!**, but you can also just mention me with **@{}**. " "If another bot is already using the **!** prefix, you can choose a different prefix " "for your server with **!settings setprefix <new_prefix>** (don't include the brackets).\n\n" "For a list of all available commands, use the **!help** command. If you want more " "information on a command, use **!help <command_name>**.\n\n" "If you have any feedback, you can use my **!feedback** command to send " "a message to my developer! If you want to request a feature, report a bug, " "stay up to date with new features, or just want some extra help, check out the official " "{} Support server! (https://discord.gg/GXCFpkr)" ).format(self.bot.user.name, guild.name, self.bot.user.name, self.bot.user.name, self.bot.user.name) await guild.owner.send(message)
def check_for_stats(osu_name): cursor.execute("SELECT osuId FROM users WHERE osuName = ?", (osu_name,)) osu_id = cursor.fetchall() if not osu_id: sender.send_message(osu_name, "Hey ! Nice to meet you, it seems to be your first time here ! Remember that this bot is also available on discord [https://discord.gg/Qsw3yD5 server] [https://discordapp.com/oauth2/authorize?client_id=318357311951208448&scope=bot&permissions=8 add the bot to your server] ! Oh and also, if you need a list of the commands avaiable, type : o!help. GL & HF") response = requests.get("https://osu.ppy.sh/api/get_user?k=" + constants.Api.osuApiKey + "&u=" + osu_name, verify=True) data = response.json() osu_id = data[0]["user_id"] cursor.execute("INSERT INTO users (osuId, osuName) VALUES (?, ?)", (osu_id, osu_name,)) conn.commit() api = OsuApi(constants.Api.osuApiKey, connector=ReqConnector()) update_stats.update_stats(0, conn, api, username = osu_name) return osu_id else: return osu_id[0][0]
def on_command_error(exception, context): #Colors Color_Off='\x1b[0m' Red='\x1b[1;31;40m' Yellow='\x1b[1;33;40m' message = context.message channel = message.channel if not message.channel.is_private and not message.content.startswith(commandPrefix + 'mute'): cursor.execute("SELECT state FROM server WHERE serverID = ?", (str(message.server.id),)) if cursor.fetchall()[0][0] == 'on': channel = message.author else: channel = message.channel errors = traceback.format_exception(type(exception), exception, exception.__traceback__) output = '' for line in errors: output += line await Log(message, content = "Message:\n" + message.content + "\n\n```" + output + "```", logLevel=2) await client.send_message(channel, "Oops ! Unexpected error :/\nGo to my personal server to ask for some help if needed !\n<https://discord.gg/Qsw3yD5>")
def addbot(self): """Provides a link that you can use to add me to a server EXAMPLE: !addbot RESULT: http://discord.gg/yo_mama""" perms = discord.Permissions.none() perms.read_messages = True perms.send_messages = True perms.manage_roles = True perms.ban_members = True perms.kick_members = True perms.manage_messages = True perms.embed_links = True perms.read_message_history = True perms.attach_files = True app_info = await self.bot.application_info() await self.bot.say("Use this URL to add me to a server that you'd like!\n{}" .format(discord.utils.oauth_url(app_info.id, perms)))
def about(self): """Tells you information about the bot itself.""" revision = os.popen(r'git show -s HEAD --format="%s (%cr)"').read().strip() result = ['**About Me:**'] result.append('- Author: Mirai [ID: 173502573205127170]') result.append('- Library: discord.py (Python)') result.append('- Latest Change: {}'.format(revision)) result.append('- Uptime: {}'.format(self.get_bot_uptime())) result.append('- Servers: {}'.format(len(self.bot.servers))) result.append('- Commands Run: {}'.format(sum(self.bot.commands_used.values()))) # statistics total_members = sum(len(s.members) for s in self.bot.servers) total_online = sum(1 for m in self.bot.get_all_members() if m.status != discord.Status.offline) unique_members = set(self.bot.get_all_members()) unique_online = sum(1 for m in unique_members if m.status != discord.Status.offline) channel_types = Counter(c.type for c in self.bot.get_all_channels()) voice = channel_types[discord.ChannelType.voice] text = channel_types[discord.ChannelType.text] result.append('- Total Members: {} ({} online)'.format(total_members, total_online)) result.append('- Unique Members: {} ({} online)'.format(len(unique_members), unique_online)) result.append('- {} text channels, {} voice channels'.format(text, voice)) result.append('') result.append('Luna server: https://discord.gg/PDmtxWq') await self.bot.say('\n'.join(result))
def on_command_error(self, ctx, error): """Error handling""" error_msg = None if isinstance(error, commands.MissingRequiredArgument): await ctx.send(error) elif isinstance(error, commands.CommandNotFound): pass elif isinstance(error, commands.CommandInvokeError): original = error.original if isinstance(original, discord.Forbidden): await ctx.send("I need to have the 'embed links' permission to send messages!") return elif isinstance(original, exceptions.Halt): return print('{0.created_at}: {0.author}: {0.content}'.format(ctx.message)) print(error) embed = discord.Embed(title="An unexpected error occured :I", colour=0xCA0147, description="If you feel like this shouldn't be happening [click here to join my support server](https://discord.gg/UP4TwFX).") await ctx.send("", embed=embed) else: print('{0.created_at}: {0.author}: {0.content}'.format(ctx.message)) print(str(error))
def info(self, message): inguilds = 0 for sever in self.servers: inguilds = inguilds + 1 response = """ **NOW ON VERSION 2!!! 100% MORE STABLE** (Finally) Type ?commands to see the commands. Add the suffix -p to disable embeds. e.g: ?commands -p Find the owner of the Bot here: <https://discord.gg/25bf5NT> also on github: <https://github.com/Carbsta/TomeBot> Hosted by @Crablabuk. To add to your server use this link: <https://discordapp.com/oauth2/authorize?client_id=247413966094073856&scope=bot&permissions=0> """ response = response +"\n\nCurrently in "+str(inguilds)+" discord server(s)." return(response)
def about(self, ctx): """Infos about the SelfBot.""" embed = discord.Embed() embed.set_author(name="Igneel's SelfBot", url="https://igneeldxd.github.io/Discord-SelfBot/") embed.description = "https://igneeldxd.github.io/Discord-SelfBot/\nThis is a Selfbot written by IgneelDxD#6666\nFor support or feedback you can join my [Server](https://discord.gg/DJK8h3n)" embed.colour = discord.Color.purple() async with aiohttp.ClientSession() as cs: async with cs.get("https://api.github.com/repos/IgneelDxD/Discord-SelfBot/commits") as resp: result = json.loads(await resp.text()) form = '[``{0}``](https://github.com/IgneelDxD/Discord-SelfBot/commit/{0}) {1} ({2})' com0 = form.format(result[0]['sha'][:7], result[0]['commit']['message'], getAgo(parser.parse(result[0]['commit']['author']['date'], ignoretz=True))) com1 = form.format(result[1]['sha'][:7], result[1]['commit']['message'], getAgo(parser.parse(result[1]['commit']['author']['date'], ignoretz=True))) embed.add_field(name='Latest Changes', value=f'{com0}\n{com1}') embed.set_thumbnail(url="https://i.imgur.com/cD51k3R.png") embed.set_footer(text='Made with discord.py | rewrite is the future!', icon_url='https://i.imgur.com/MyEXmz8.png') await edit(ctx, embed=embed) # User info on Server
def kick(self, ctx, member, *, reason="No reason was given."): """Kick a member.""" found_member = self.find_user(member, ctx) if found_member == ctx.message.author: return await ctx.send("You can't kick yourself, you absolute fucking dumbass.") elif not found_member: await ctx.send("That user could not be found.") else: reason_msg = "The given reason was: `{}`".format(reason) try: await found_member.send("You have been kicked by user {0.name}#{0.discriminator}.\n{2}\nYou can rejoin the server with this link: https://discord.gg/hHHKPFz".format(ctx.message.author, self.bot.rules_channel.mention, reason_msg)) except discord.errors.Forbidden: pass audit_reason = reason + " This action was done by: " + ctx.message.author.name await found_member.kick(reason=audit_reason) await ctx.send("Successfully kicked user {0.name}#{0.discriminator}!".format(found_member)) embed = discord.Embed(description="<@{0.id}> | {0.name}#{0.discriminator} kicked user <@{1.id}> | {1.name}#{1.discriminator}".format(ctx.message.author, found_member)) embed.add_field(name="Reason given", value="• " + reason) await self.bot.cmd_logs_channel.send(embed=embed)
def about(self, ctx, txt: str = None): """Links to the bot's github page.""" if embed_perms(ctx.message) and txt != 'short': em = discord.Embed(color=0xad2929, title='\ud83e\udd16 Appu\'s Discord Selfbot', description='**Features:**\n- Custom commands/reactions\n- Save last x images in a channel to your computer\n- Keyword notifier\n' '- Set/cycle your game status and your avatar\n- Google web and image search\n- MyAnimeList search\n- Spoiler tagging\n' '- Server info commands\n- Quoting, calculator, creating polls, and much more') em.add_field(name='\ud83d\udd17 Link to download', value='[Github link](https://github.com/appu1232/Discord-Selfbot/tree/master)') em.add_field(name='\ud83c\udfa5Quick examples:', value='[Simple commands](http://i.imgur.com/3H9zpop.gif)') if txt == 'link': em.add_field(name='?? Discord Server', value='Join the official Discord server [here](https://discord.gg/FGnM5DM)!') em.set_footer(text='Made by appu1232#2569', icon_url='https://i.imgur.com/RHagTDg.png') await ctx.send(content=None, embed=em) else: await ctx.send('https://github.com/appu1232/Selfbot-for-Discord') await ctx.message.delete()
def help_embed_all(self, prefix, commands): """Create an embed message that displays command help""" help = discord.Embed(title="Available Commands", color=constants.BLUE) help.description = ("**Note:** don't include the angled brackets\n" + "For additional help, join the support server: https://discord.gg/ZqkjJEa") help.set_footer(text="Use {}help [command] for more info on a command".format(prefix)) for command in commands: if command.hidden: continue signature = self.get_command_signature(prefix, command) help.add_field(name="{}".format(signature), value="{}".format(command.help.split('\n')[0]), inline=False) return help
def about(self, ctx): """Show the stuff about me! I promise I'm interesting uwu **Usage:** `g_about [credits]` **Permission:** User""" args = ctx.message.content args = args.split(' ') member_count = 0 server_count = len(self.bot.guilds) for server in self.bot.guilds: for member in server.members: member_count += 1 abtEm = discord.Embed(title='About Godavaru!', description=abtDesc, color=0x9B59B6) abtEm.add_field(name='Version Number', value='{}'.format(self.bot.version), inline=False) abtEm.add_field(name='Servers', value=str(server_count)) abtEm.add_field(name='Users',value=str(member_count) + '\n\n[Invite me](https://goo.gl/chLxM9)\n[Support guild](https://discord.gg/ewvvKHM)\n[Patreon page](https://www.patreon.com/godavaru)', inline=False).set_footer(text="Made with love <3 | Check out g_about credits for special credits.").set_thumbnail(url="https://cdn.discordapp.com/avatars/311810096336470017/fa4daf0662e13f25bdbd09fd18bdc36d.png") try: if args[1] == "credits": embed = discord.Embed(title="Special Recognition",description="" +"**Primary Developer:** Desiree#3658\n" +"**Developers:** Yuvira#7655, AttributeError#2513, and Jonas B.#9089\n" +"**Sensei:** Yuvira#7655\n" +"**Emotional Support & Boyfriend:** MrLar#8117\n" +"**Inspiration:** Kodehawa#3457 (`and MantaroBot, if it wasn't for that project I probably would never have tried to make a bot`)\n\n" +"And thanks to everyone who has used the bot. Much love <3", color=0x1abc9c) else: embed = abtEm except IndexError: embed = abtEm await ctx.send(content=None, embed=embed)
def invite(self, ctx): """Get some important links about me. **Usage:** `g_invite` **Permission:** User""" embed = discord.Embed(description='Here are some useful links for the Godavaru bot. If you have any questions at all, feel free to join the support guild and tag Desiree#3658 with your questions!\nBelow you can also find the links to the support guild itself and the Patreon URL. Thanks for using the bot!', color=0x9B59B6).set_author(name='Useful Links for Godavaru!', icon_url='https://cdn.discordapp.com/avatars/311810096336470017/fa4daf0662e13f25bdbd09fd18bdc36d.png').add_field(name='Invite URL', value='http://polr.me/godavaru').add_field(name='Support Guild', value='https://discord.gg/ewvvKHM').add_field(name="Patreon URL", value='https://patreon.com/godavaru').add_field(name="Github", value="https://github.com/Desiiii/Godavaru") await ctx.send(content=None, embed=embed)
def link_user(ctx): rank, channel, message = await init_command(ctx.message) if rank in ['USER', 'ADMIN', 'MASTER']: parameters = message.content.replace(commandPrefix + 'link_user ', '') results = get_user(user = parameters, me = False) stats = [] if not (results == []): for item in results[0]: stats.append(item) osuId = stats[16][1] osuUsername = stats[17][1] cursor.execute("SELECT * FROM users WHERE discordId = ?", (str(message.author.id),)) if not cursor.fetchall(): key = userlink.generate_new_key(osuId, message.author.id) if message.channel.is_private == False: embed = discord.Embed(title = "Link account", description = "Please check your private messages to get your key and the instructions to link your account to uso !", colour = 0x3498db) await client.send_message(channel, embed = embed) embed = discord.Embed(title = "Link account", colour = 0x3498db, description="Please open <:osu:310362018773204992> and send me __**``pass {}``**__\nMy ingame name is __UsoBot__ -> [profile](https://osu.ppy.sh/u/10406668)\nBe careful, this key will __expire in 10 min__".format(key)) await client.send_message(message.author, embed = embed) else: await client.send_message(channel, "Sorry, you already linked your account ! If you have a problem, please contact Renondedju\n? <https://discord.gg/Qsw3yD5>") else: await client.send_message(channel, "Oups sorry, didn't find this user\n*Try with your osu id instead or the link to your profile*") else: missing_permissions_message(channel)
def on_server_join(server): try: cursor.execute("INSERT INTO server (serverID, state) VALUES (?, ?)", (server.id, 'off')) conn.commit() except sqlite3.IntegrityError: print ("Already in database") embed = discord.Embed(title = "Hi there !", description="**Nice to meet you, I'm Uso!**\nMy command prefix is ``" + commandPrefix + "``\nIf you want to know what am i capable of, try ``" + commandPrefix + "help``\nAdmins : you can mute me if needed by doing ``" + commandPrefix + "mute on``\n\nAdd the bot to your server [Here](https://discordapp.com/oauth2/authorize?client_id=318357311951208448&scope=bot&permissions=8)\nI'm also avaiable ingame ! Look for UsoBot\nYou can come to my own server to have some help if nedded or even support the devs :D\n?https://discord.gg/Qsw3yD5\n\n:heart::heart::heart:Have fun evryone !:heart::heart::heart:") embed.set_thumbnail(url = "https://cdn.discordapp.com/avatars/"+str(client.user.id)+"/"+str(client.user.avatar)+".png") message = await client.send_message(client.get_server(server.id), embed = embed) await Log(message, logLevel = 1, thumbnailUrl = server.icon_url, content = "**I've been added to a new server !**\n__Server name :__ **" + str(server.name) + "**\n__Server Id :__ **" + str(server.id) + "**\n__Users :__ **" + str(server.member_count) + "**\n__Owner name :__ **" + str(server.owner.name) + "**")
def help_message(): """ :return: """ help_text = """ **RERO** *The multipurpose utility bot for Discord.* Commands ```ruby . ?names : List of detected name changes ?pm [on, off, 24/7] : Sends you PM if you get mentioned ?8ball question : Answers a question 8 ball style ?sr subreddit : Grab random image from the subreddit ?anime name : Grab a anime from MAL ?manga name : Grab a manga from MAL ?ud query : Urban Dictionary definition ?wiki query : Wikipedia summary of querry ?giphy query : Gif matching querry ?xkcd [number] : Random xkcd or specify a number ?weather city : Get weather information
For a complete list of functions (*too many to send by PM*), Want Rero in your server too? <https://discordapp.com/oauth2/authorize?client_id=314796406948757504&scope=bot&permissions=8> Visit RERO's Server: https://discord.gg/nSHt53W """ return help_text
```
def on_ready(): print('Logged in as') print(bot.user.name) print(bot.user.id) print('------') invite = discord.Game(name="https://discord.gg/VsrbrYC", url=None, type=0) await bot.change_presence(game=invite)
def show_page(self, page, *, first=False): self.current_page = page entries = self.get_page(page) self.embed.clear_fields() self.embed.description = self.description self.embed.title = self.title if hasattr(self, '_is_bot'): value ='For more help, join the official bot support server: https://discord.gg/pYuKF2Z' self.embed.add_field(name='Support', value=value, inline=False) self.embed.set_footer(text=f'Use "{self.prefix}help command" for more info on a command.') signature = _command_signature for entry in entries: self.embed.add_field(name=signature(entry), value=entry.short_doc or "No help given", inline=False) if self.maximum_pages: self.embed.set_author(name=f'Page {page}/{self.maximum_pages} ({self.total} commands)') if not self.paginating: return await self.channel.send(embed=self.embed) if not first: await self.message.edit(embed=self.embed) return self.message = await self.channel.send(embed=self.embed) for (reaction, _) in self.reaction_emojis: if self.maximum_pages == 2 and reaction in ('\u23ed', '\u23ee'): # no |<< or >>| buttons if we only have two pages # we can't forbid it if someone ends up using it but remove # it from the default set continue await self.message.add_reaction(reaction)
def _make_list_embed(self, streamers, subscriber): streams = '\n'.join(f'[{username}]({self.stream_url(username)})' for (username,) in streamers) if len(streams) > 1024: log.warning('Embed value length is over 1024!') return discord.Embed( description='Please complain about embed pagination in https://discord.gg/xrzJhqq', color=discord.Color.red() ) embed = discord.Embed(description=streams, color=discord.Color.blue()) embed.set_author(name=f"{self.service_name.capitalize()} subscriptions for {subscriber}") return embed
def support_invite(self): # The following is the link to the bot's support server. # You are allowed to change this to be another server of your choice. # However, doing so will instantly void your warranty. # Change this at your own peril. return 'https://discord.gg/WtkPTmE'
def anonCheck(self, msg): if msg.author == self.client.user: return False elif msg.channel.id == self.hc.id or msg.channel.id == self.sc.id: return True else: return False # AskPatch is designed for discord.gg/patchgaming but you may edit it # for your own personal uses if you like # the database fields are: # Single table: # varchar(20) author, vc(20) id, TIMESTAMP time, TEXT content, BOOL used, # INT(11)PK entryid, BOOL approved
def help(self, ctx, *, architecture: str = None): """ Prints help """ me = ctx.guild.me if architecture is None: embed = self._embed(ctx, "Assembler help", "To invoke Assembler, call {} assemble `<architecture>` `<assembly code block>`. For help, call {} help or {} help `[architecture]` to show how" " to assemble for given architecture. Source code of the bot is available [on Emzi's GitHub](https://github.com/Emzi0767/Discord-ASM-Bot). To" " invite the bot to your server, Follow [this invite link]" "(https://discordapp.com/oauth2/authorize?client_id=283200903937261569&scope=bot&permissions=0). For more help or support, join [Emzi's server]" "(https://discord.gg/rGKrJDR).".format(me.mention, me.mention, me.mention), "info") embed.add_field(name="Example", value=me.mention + " assemble x86 ```x86asm\nmov eax, sp\n```", inline=False) archstr = "• " + "\n• ".join(x.display_name for x in self._archmap) embed.add_field(name="Available architectures", value=archstr, inline=False) else: arch = None for xarch in self._archmap: if xarch.display_name == architecture: arch = xarch if arch is None: raise Exception("Unknown architecture specified") embed = self._embed(ctx, "Architecture help", "Architecture name: {}\nArchitecture full name: `{}`".format(arch.display_name, arch.clang_name)) archstr = ", ".join("`{}`".format(x) for x in arch.names) embed.add_field(name="Architecture aliases", value=archstr, inline=False) await ctx.channel.send(embed=embed)
def ex(args, message, client, invoke): args_out = "" if len(args) > 0: args_out = "\n\n*Attached arguments: %s*" % args.__str__()[1:-1].replace("'", "") yield from client.send_message(message.channel, "Check your direct messages! I slid in!") yield from client.send_message(message.author, "Hey! Thanks for typing ?help, here's a list of commands which should hopefully be of some use to you - here they are:\n\n**?ping** - Returns a message saying 'PONG!'\n**?help** - Sends you this message.\n\nMore to come in the future!\n\nBot coded by: Tobyy\nOfficial Support Server: https://discord.gg/VurEzsA\n\nEnjoy!")
def __init__(self, bot_class, *args, **kwargs): self.bot_class = bot_class self.chat_ids = {} self.shards = {} self.extensions = {} self.shard_tasks = {} self.shard_connect_failures = {} self.shard_count = 0 self.loop = asyncio.get_event_loop() self.config = self._read_config("config.json") self.credentials = self._read_config("credentials.json") self.description = kwargs.pop("description", "\nHsss! Checkout the support command the join the official server!\n") self.pm_help = kwargs.pop("pm_help", False) self.help_attrs = kwargs.pop("help_attrs", dict(hidden=True)) self.command_not_found = kwargs.pop("command_not_found", "\N{WARNING SIGN} Whoops, '{}' doesn't exist!") self.command_has_no_subcommands = kwargs.pop("command_has_no_subcommands", "\N{WARNING SIGN} Sorry, '{0.name}' doesn't have '{1}'") self.invite_url = "https://discord.gg/qC4ancm" self.kwargs = kwargs self.args = args self.kwargs.update({ "description": self.description, "pm_help": self.pm_help, "help_attrs": self.help_attrs, "command_not_found": self.command_not_found, "command_has_no_subcommands": self.command_has_no_subcommands, "shard_count": self.shard_count }) self.log = logging.getLogger() self.log.setLevel(logging.DEBUG) self.log.addHandler( logging.FileHandler(filename="snake.log", encoding="utf-8", mode='w') )
def changelog(): """Gives a URL to the current bot changelog.""" await bot.say('https://discord.gg/y2PcWMM') #loads bot credentials.json as file. Takes client_id, carbon_key and bots_key=client_id now (i will fix it) #if id is missing, it wont load the file
def server(self, ctx): """ Invite like to the bot's support server """ await ctx.send("<http://discord.bot.neverendinggaf.com> - https://discord.gg/ddbFt7S")
def info(self, ctx): """Prints info about mangobyte""" github = "https://github.com/mdiller/MangoByte" python_version = "[Python {}.{}.{}]({})".format(*os.sys.version_info[:3], "https://www.python.org/") discordpy = "https://github.com/Rapptz/discord.py" embed = discord.Embed(description="The juiciest unsigned 8 bit integer you eva gonna see", color=discord.Color.green()) embed.set_author(name=self.bot.user.name, icon_url=self.bot.user.avatar_url, url=github) embed.add_field(name="Development Info", value=( "Developed as an open source project, hosted on [GitHub]({}). " "Implemented using {} and a python discord api wrapper [discord.py]({})".format(github, python_version, discordpy))) embed.add_field(name="Features", value=( "• Answers questions (`?ask`)\n" "• Plays audio clips (`?play`, `?dota`)\n" "• Greets users joining a voice channel\n" "• For a list of command categories, try `?help`")) help_guild_link = "https://discord.gg/d6WWHxx" embed.add_field(name="Help", value=( f"If you want to invite mangobyte to your server/guild, click this [invite link]({invite_link}). " f"If you have a question, suggestion, or just want to try out mah features, check out the [Help Server/Guild]({help_guild_link}).")) owner = (await self.bot.application_info()).owner embed.set_footer(text="MangoByte developed by {}".format(owner.name), icon_url=owner.avatar_url) await ctx.send(embed=embed)
def invite(self): await self.bot.reply('https://discord.gg/TVA9Z38') await self.bot.replied(context)
def server(self, ctx): text = "**Support Server**\n\nIf you're encountering a problem with Tuxedo, or just wanna drop by, use this Discord link to join the official Tuxedo server.\n\nLink => https://discord.gg/KEcme4H" try: await ctx.author.send(text) await ctx.send(":mailbox_with_mail: Check your DMs.") except discord.Forbidden: await ctx.send(text)
def clean_invite_embed(line): """Makes invites not embed""" return line.replace("discord.gg/", "discord.gg/\u200b")
def __init__(self, bot): self.bot = bot self.invites = ['discord.gg/', 'discordapp.com/invite/'] self.invite_domains = ['discord.gg', 'discordapp.com']
def about(self, ctx): """Display information about the bot itself This command was adapted from RoboDanny by Rapptz - https://www.github.com/Rapptz/RoboDanny """ manager = MessageManager(self.bot, ctx.author, ctx.channel, ctx.prefix, [ctx.message]) e = discord.Embed(title='Spirit v{}'.format(constants.VERSION), colour=constants.BLUE) e.description = ("[Invite Spirit](https://discordapp.com/oauth2/authorize?client_id=335084645743984641&scope=bot&permissions=523344)\n" + "[Spirit Support Server](https://discord.gg/GXCFpkr)") owner = self.bot.get_user(118926942404608003) e.set_author(name=str(owner), icon_url=owner.avatar_url) # statistics total_members = sum(1 for _ in self.bot.get_all_members()) total_online = len({m.id for m in self.bot.get_all_members() if m.status is discord.Status.online}) total_unique = len(self.bot.users) voice_channels = [] text_channels = [] for guild in self.bot.guilds: voice_channels.extend(guild.voice_channels) text_channels.extend(guild.text_channels) text = len(text_channels) voice = len(voice_channels) e.add_field(name='Members', value='{} total\n{} unique\n{} unique online'.format(total_members, total_unique, total_online)) e.add_field(name='Channels', value='{} total\n{} text\n{} voice'.format(text + voice, text, voice)) memory_usage = "%0.2f" % (self.process.memory_full_info().uss / 1024**2) cpu_usage = "%0.2f" % (self.process.cpu_percent() / psutil.cpu_count()) e.add_field(name='Process', value='{} MiB\n{}% CPU'.format(memory_usage, cpu_usage)) e.add_field(name='Guilds', value=len(self.bot.guilds)) e.add_field(name='Commands Run', value=self.bot.command_count) e.add_field(name='Uptime', value=self.get_bot_uptime(brief=True)) e.set_footer(text='Made with discord.py', icon_url='http://i.imgur.com/5BFecvA.png') await manager.say(e, embed=True, delete=False) await manager.clear()
def about(self, ctx): """Tells you information about the bot itself.""" cmd = r'git show -s HEAD~3..HEAD --format="[{}](https://github.com/Rapptz/RoboDanny/commit/%H) %s (%cr)"' if os.name == 'posix': cmd = cmd.format(r'\`%h\`') else: cmd = cmd.format(r'`%h`') revision = os.popen(cmd).read().strip() embed = discord.Embed(description='Latest Changes:\n' + revision) embed.title = 'Official Bot Server Invite' embed.url = 'https://discord.gg/0118rJdtd1rVJJfuI' embed.colour = discord.Colour.blurple() owner = self.bot.get_user(self.bot.owner_id) embed.set_author(name=str(owner), icon_url=owner.avatar_url) # statistics total_members = sum(1 for _ in self.bot.get_all_members()) total_online = len({m.id for m in self.bot.get_all_members() if m.status is discord.Status.online}) total_unique = len(self.bot.users) voice_channels = [] text_channels = [] for guild in self.bot.guilds: voice_channels.extend(guild.voice_channels) text_channels.extend(guild.text_channels) text = len(text_channels) voice = len(voice_channels) embed.add_field(name='Members', value=f'{total_members} total\n{total_unique} unique\n{total_online} unique online') embed.add_field(name='Channels', value=f'{text + voice} total\n{text} text\n{voice} voice') memory_usage = self.process.memory_full_info().uss / 1024**2 cpu_usage = self.process.cpu_percent() / psutil.cpu_count() embed.add_field(name='Process', value=f'{memory_usage:.2f} MiB\n{cpu_usage:.2f}% CPU') embed.add_field(name='Guilds', value=len(self.bot.guilds)) embed.add_field(name='Commands Run', value=sum(self.bot.command_stats.values())) embed.add_field(name='Uptime', value=self.get_bot_uptime(brief=True)) embed.set_footer(text='Made with discord.py', icon_url='http://i.imgur.com/5BFecvA.png') await ctx.send(embed=embed)
def info(self): """Shows info about Red""" author_repo = "https://github.com/Twentysix26" red_repo = author_repo + "/Red-DiscordBot" server_url = "https://discord.gg/red" dpy_repo = "https://github.com/Rapptz/discord.py" python_url = "https://www.python.org/" since = datetime.datetime(2016, 1, 2, 0, 0) days_since = (datetime.datetime.utcnow() - since).days dpy_version = "[{}]({})".format(discord.__version__, dpy_repo) py_version = "[{}.{}.{}]({})".format(*os.sys.version_info[:3], python_url) owner_set = self.bot.settings.owner is not None owner = self.bot.settings.owner if owner_set else None if owner: owner = discord.utils.get(self.bot.get_all_members(), id=owner) if not owner: try: owner = await self.bot.get_user_info(self.bot.settings.owner) except: owner = None if not owner: owner = "Unknown" about = ( "This is an instance of [Red, an open source Discord bot]({}) " "created by [Twentysix]({}) and improved by many.\n\n" "Red is backed by a passionate community who contributes and " "creates content for everyone to enjoy. [Join us today]({}) " "and help us improve!\n\n" "".format(red_repo, author_repo, server_url)) embed = discord.Embed(colour=discord.Colour.red()) embed.add_field(name="Instance owned by", value=str(owner)) embed.add_field(name="Python", value=py_version) embed.add_field(name="discord.py", value=dpy_version) embed.add_field(name="About Red", value=about, inline=False) embed.set_footer(text="Bringing joy since 02 Jan 2016 (over " "{} days ago!)".format(days_since)) try: await self.bot.say(embed=embed) except discord.HTTPException: await self.bot.say("I need the `Embed links` permission " "to send this")
def planifie(channel_obj: discord.Channel = None): now = int(time.time()) thisDay = now - (now % 86400) seconds_left = 86400 - (now - thisDay) multiplicator = round(seconds_left / 86400, 5) if not channel_obj: logger.debug("Replanning") commons.bread = defaultdict(int) planification_ = {} if multiplicator == 0: multiplicator = 1 servers = prefs.JSONloadFromDisk("channels.json") for server_ in list(servers.keys()): server = bot.get_server(str(server_)) if not server: logger.debug("Non-existant server: " + str(server_)) servers.pop(server_) scores.delServerPlayers(sid=server_) elif not "channels" in servers[server.id]: await comm.logwithinfos(server.default_channel, log_str="Server not configured: " + server.id) try: await bot.send_message(server, "The bot is not configured properly, please check the config or contact Eyesofcreeper#4758 | https://discord.gg/2BksEkV") await comm.logwithinfos(server.default_channel, log_str="Unconfigured message sent...") except: await comm.logwithinfos(server.default_channel, log_str="Error sending the unconfigured message to the default channel on the server.") else: for channel_ in servers[server.id]["channels"]: channel = server.get_channel(str(channel_)) if channel: permissions = channel.permissions_for(server.me) if permissions.read_messages and permissions.send_messages: # logger.debug("Adding channel: {id} ({ducks_per_day} c/j)".format(**{ # "id" : channel.id, # "ducks_per_day": prefs.getPref(server, "ducks_per_day") # })) planification_[channel] = round(prefs.getPref(server, "ducks_per_day") * multiplicator) else: await comm.logwithinfos(channel, log_str="Error adding channel to planification: no read/write permissions!") else: pass commons.ducks_planned = planification_ # {"channel":[time objects]} prefs.JSONsaveToDisk(servers, "channels.json") else: commons.bread[channel_obj] = 0 permissions = channel_obj.permissions_for(channel_obj.server.me) if permissions.read_messages and permissions.send_messages: pass else: await comm.logwithinfos(channel_obj, log_str="Error adding channel to planification: no read/write permissions!") commons.ducks_planned[channel_obj] = round(prefs.getPref(channel_obj.server, "ducks_per_day") * multiplicator)
def cleanup_servers(self, ctx): language = prefs.getPref(ctx.message.server, "language") await comm.message_user(ctx.message, _("Serching for servers to leave", language)) to_clean = [] total_members_lost = 0 servers = JSONloadFromDisk("channels.json") for server in list(self.bot.servers): try: if len(servers[server.id]["channels"]) == 0: to_clean.append(server) total_members_lost += server.member_count except KeyError: # Pas de channels ou une autre merde dans le genre ? to_clean.append(server) total_members_lost += server.member_count def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) random_str = id_generator() await comm.message_user(ctx.message, _("Cleaning {servers} unused servers (accounting for {members} members in total)", language).format(servers=len(to_clean), members=total_members_lost)) await comm.message_user(ctx.message, _("To confirm, please type {random_str} now.", language).format(random_str=random_str)) def is_random_str(m): return m.content == random_str guess = await self.bot.wait_for_message(timeout=10.0, author=ctx.message.author, check=is_random_str) if guess is None: await comm.message_user(ctx.message, _(":x: Operation cancelled, you took too long to answer.", language)) else: failed = 0 for server in to_clean: try: await self.bot.send_message(server, ":warning: I'm leaving the server, as you haven't configured me.\nJoin the DuckHunt server (https://discord.gg/2BksEkV) to get help with the setup and what you have to do to bring me back (and get me to stay), or check out https://api-d.com.") except: failed += 1 pass try: await self.bot.leave_server(server) # Good Bye :'( except: commons.logger.exception("") await comm.message_user(ctx.message, _(":ok: Finished, failed for {failed} servers.", language).format(failed=failed)) # await self.bot.leave_server(server)
def about(self, ctx): """Info about bot.""" cmd = r'git log -3 --pretty="[{}](https://github.com/khazhyk/dango.py/commit/%H) %s (%ar)"' if os.name == "posix": cmd = cmd.format(r'\`%h\`') else: cmd = cmd.format('`%h`') stdout, _ = await utils.run_subprocess(cmd) embed = discord.Embed(description='Latest Changes:\n' + stdout) embed.title = "spoo.py Server Invite" embed.url = "https://discord.gg/0j3CB6tlXwou6Xb1" embed.color = 0xb19bd9 embed.set_author( name=ctx.bot.user.name, icon_url=ctx.bot.user.avatar_url) embed.set_thumbnail(url=ctx.bot.user.avatar_url) servers = len(ctx.bot.guilds) members = sum(len(g.members) for g in ctx.bot.guilds) members_online = sum(1 for g in ctx.bot.guilds for m in g.members if m.status != discord.Status.offline) text_channels = sum(len(g.text_channels) for g in ctx.bot.guilds) voice_channels = sum(len(g.voice_channels) for g in ctx.bot.guilds) memory = psutil.Process(os.getpid()).memory_full_info().rss / (1024 * 1024) # messages = 10 # commands = 10 embed.add_field( name="Members", value="%d total\n%d online" % (members, members_online)) embed.add_field( name="Channels", value="%d text\n%d voice" % (text_channels, voice_channels)) embed.add_field(name="Servers", value=servers) embed.add_field(name="Process", value="%.2fMiB RSS\n%s Uptime" % (memory, uptime())) embed.set_footer(text="dangopy | discord.py v{}".format(discord_version)) # embed.add_field(name="Messages", value="%d messages\n%d commands" % (messages, commands)) # embed.add_field(name="Shards", value=shard_id(ctx.bot)) await ctx.send(embed=embed)