#discord-bots
1 messages Β· Page 960 of 1
you can store the currently running games in a variable and check to see if one's running
assuming the game doesnt last for too long
Nice selfie π€©
My idea was to make a queue
where one player is waiting for the other from an other server
You are coding a game on discord ?
you have to creat a list like list = [« sus »]
nah only a random choice which seems like a minigame
well what did you try? and what version of dpy are you running? dpy 2.0 and forks of dpy like disnake offer discord's new timeout feature which would be suitable for doing mutes
user = message.author
role = get(user.server.roles, name="Muted")
await client.add_roles(user, role)
@slate swan Add me to be friend I have a part of my code that I can send to you. My pc is off so I will help you tomorrow
whats the standard right now for virtual environments
I know what you mean
client.add_roles is extremely outdated and has been replaced with Member.add_roles(<one or more roles>)
oooooooh
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
oh yes
message.author means that itβs the author of the message so it works with it
yeah that would probably be a good idea, although after two players connect then you'll still want a way for your game to run; this could be done with a custom class that keeps track of game variables and listening for messages from the appropriate players
Add me I will help you tomorrow
if the message came from a guild then the author will be a Member object, so the add_roles method would come from that
oh
may you send me an example of your idea?
My bad
Where do I get the docs for Buttons, TextInputs et
buttons are in master docs
oh okay, that's why I'm lost
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
you'll find the rest there
how do i specify the role like discord.Member.add_roles('mute') or something?
sweet
How can I limit someone from using a command if they already used it and it is still running?
@hushed galleon so code example
minigame_queue = []``` for simplicity a list could be used as your queue, and you might append either a user or a (user, channel) tuple to it, whatever you might need, then your class might look like this ```py
class Minigame:
def __init__(self, bot, player_channels): ...
# store whatever attributes you may need such as the bot,
# or the players and the channels they're in
# if you need to write helper functions for your game,
# this class can keep them organized in one place
async def start(self):
# send a message to each player...
# wait for player A's turn... (see wait_for docs)
message = await self.bot.wait_for('message', check=check)
# ...and anything else here``` then you could use the queue and class in your command ```py
@bot.command()
async def join_minigame(ctx):
# add the player to queue if they are the first one
if not minigame_queue:
minigame_queue.append(ctx.author)
return
# otherwise pick the first player in queue
other_player = minigame_queue.pop(0)
# then start the minigame
my_game = Minigame(bot, [ctx.author, other_player])
await my_game.start()```
you could do something similar to what you had before with discord.utils.get, only difference is that the server attribute should be named guild instead
!d discord.ext.commands.max_concurrency < you can use this decorator to limit the command on a per-user basis
@discord.ext.commands.max_concurrency(number, per=discord.ext.commands.BucketType.default, *, wait=False)```
A decorator that adds a maximum concurrency to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses.
This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket β only a set number of people can run the command.
New in version 1.3.
if they exceed the max number then the decorator raises a commands.MaxConcurrencyReached error
what is the * there for and where do I put that in my code? below, above, or inside my command class?
!args-kwargs
*args and **kwargs
These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.
Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.
Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.
Use cases
β’ Decorators (see !tags decorators)
β’ Inheritance (overriding methods)
β’ Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
β’ Flexibility (writing functions that behave like dict() or print())
See !tags positional-keyword for information about positional and keyword arguments
the * means any parameters after it are keyword only, and its something you can do in your own functions
e.g. ```py
def add(*, x, y):
return x + y
now you are required to use keyword arguments
add(x=1, y=2)
3```
and max_concurrency is a check decorator so it would be on top of your command: py @bot.command() @commands.max_concurrency(1, commands.BucketType.user) async def my_command(ctx): ...
fuck it since i cant get it working ill just make it ban people 
Okay, I got it working, thank you!!
what are you talking about
That's me
thx dude
hey uhh this code is only mentioning the bot who sent that message
bot.mention for bot in ctx.guild.members if bot.bot```
its supposed to show the others too
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
this is the bots embed guildinfoEmbed.add_field(name='Bots', value=', '.join(list_of_bots), inline=False)
Because of the if part
huh ??
βIf bot.botβ
yeah lol
what do i change it to
So it only adds all members that are bots
So it mentions all users?
no i mean so it mentions every bot in the server
https://hypixel.net/||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β|| https://i.e-z.host/ββ ββββ β ββββ ββ βββββββββββββββββ β
And what's it doing right now?
only mentioning the bot
Which bot?
https://hypixel.net/||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β|| https://i.e-z.host/βββ ββ ββββ ββββββββββ β β β ββ β ββ β βββ
my own bot
Is that the only bot in the server?
nope
Then it's probably an intents issue
intents issue?
Yes.
should i send code
See here
uhh u cant use intents in brakcets
bro but thats me
If someone from Israel please dm me
What?
yeah if you dont have the members intent enabled, discord.py cant offer you a list of members in the guild and the discord API will prevent you from requesting them
Just applied for verified bot, how long does the response usually take?
https://hypixel.net/||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β|| https://i.e-z.host/β ββ ββββ ββ βββ βββββ ββββ βββββ βββ ββ
@commands.command()
@has_permissions(ban_members =True)
async def ban(self, ctx, member: disnake.Member = None, *, reason = None):
logsChannel = self.bot.get_channel(877143830955180102)
if member == None:
embed = disnake.Embed(
title=f'Errore',
color=disnake.Color.from_rgb(255, 1, 57),
description=":x: Devi specificare un membro da bannare per poter usare questo comando!"
)
await ctx.reply(embed=embed)
elif member != None:
embed = disnake.Embed(
title=f'Membro {member.name}#{member.discriminator} bannato!',
description=f"{member.name}#{member.discriminator} Γ¨ stato bannato da {ctx.author.name}#{ctx.author.discriminator}",
color=disnake.Color.from_rgb(255, 1, 57),
timestamp=datetime.datetime.utcnow()
)
embed.set_author(
name=f"Comando eseguito da {ctx.author.name}#{ctx.author.discriminator}"
)
await member.ban(reason=reason)
await logsChannel.send(
f"`[{datetime.datetime.utcnow().strftime('%H:%M:%S | %d-%m-%Y')}]` **{ctx.author.name}#{ctx.author.discriminator}**\n(ID:{ctx.author.id}) ha bannato un utente:",
embed=embed
)
when I try to ban nothing happens, I don't get any errors, can you help me?
wtf??
Does [{datetime.datetime.utcnow().strftime('%H:%M:%S | %d-%m-%Y')}] give it in unix?
when I remove await member.ban everything works fine
according to danny's recent gist, 1-3 months
https://gist.github.com/Rapptz/c4324f17a80c94776832430007ad40e6
No I am just asking you something
My friends said like 1-3 weeks
What are you sending me lol
I applied my bot for verified
@glad cradle It's a question
is a datetime object so it can be transformed and formatted with strftime
To what?
to str
iunno i dont actually have knowledge in their verification process
yeah lol
They say 3-5 days
Ohh
Though they often get behind
My bot is growing like 20 servers a day, it's a 100 now so can't grow till it's verified :/
@sick birch could you help me maybe? π¬π£
Sure. Do you have on_command_error anywhere at all in your code?
A quick question for the mods,
can I post here that I'm looking for a partner to help me develop a discord bot using python or is it against any of the rules?
That falls under rule 6, so no
Ah. I know why. You can't compare an object to None using == I don't think
I figured it would be something like that, even though i'm technically not interested in advertising the project itself, but looking only for a partner
nah that should work fine, its only unconventional to compare to none with the equality operator
figured it out with an errors handler
Command raised an exception: Forbidden: 403 Forbidden (error code: 60003): Two factor is required for this operation
Ah
the server requires 2FA which means the bot dev also needs to have 2FA as well
first time ive seen that error message
File "c:\Users\acatto\Desktop\NSB\main.py", line 9, in <module>
from discord.ext import commands, tasks
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
umm
the Bot*
I already have 2fa active
sure you downloaded the real Discord.py?
yes
sure you just don't have a file named discord in the same place as main.py?
https://hypixel.net/||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β||||β|| https://i.e-z.host/β ββ ββββββ ββ ββββββ β βββββ βββββ ββ β
should i pip uninstall discord and install it again
Give that a try
imma try nextcord
are you sure you have it enabled? thats the only restriction according to the discord docs https://discord.com/developers/docs/topics/oauth2#twofactor-authentication-requirement
@sick birch What would you say that is the easiest way to get slash commands without changing too much of your code
thx I figure it out
minigame_queue is not definied so how to define it?
just writing it somewhere in your global scope is fine, or as a bot var if you have a cog and want it to persist across cog reloads
but how to define it?
@hushed galleon :white_check_mark: Your eval job has completed with return code 0.
123
!e
code
!eval <code>
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'discord' is not defined
!e
test = "discord.py is confusing"
print(test)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
discord.py is confusing

u lying ofc, how it can be you when it's me
Could u copy paste it, I'm way too blind to read otherwise
pipinstaller : The term 'pipinstaller' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and
try again.
At line:1 char:1
- pipinstaller getuuid.py
-
+ CategoryInfo : ObjectNotFound: (pipinstaller:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
What are trying to do 
Convert his code to .exe
py - exe
Why though
to get uuid
???
it'll print it in cmd promt
Think you NEED it before doing it
yeah i do
c# is such a fine language π°
From where?
its for a whitelist and blacklist system so i can blacklist ur uuid
For a discord bot?
yh
Lol this be lagging discord
Why do you need uuid then?
I don't see why you need an executable for that
no like
^
kk
Putting an interpreted language into an executable only adds more overhead
For some reason some think it's a good thing to make your bot executable
this leads just to more headaches
People seem to want to put everything into an executable
I can understand that since it's all in one nice package but unfortunately that's not how interpreted languages work
"It's cool" 
If you want everything to be in one nice little executable file, you should program in a compiled language
Just ship the python bytecode kek
Don't you still need the interpreter for that
You would still need the interpreter so itβs totally useless
Yes
Thought so
The only time I've seen a need for converting python files to executables is when someone writes a malware in python, and sending a py file would be too easy to figure out
Make a python program that takes python code interpreting it to C then compile that kek
nice tip
shit
Kind of weird to require UUID whitelisting for a discord bot
time to get demoted for rule 5
Leaves me to believe the bot was made for malicious purposes
@hushed galleon sorry got it but what to put in the list?
πΏ time to ping the mods
Nah. They probably just want a whitelist/blacklist system
so meant user but how to put a user in this list
A normal bot wouldβve use discord IDs?
UUID is strange yes, you could just use their discord ID
It has more use cases.. for example if you want people to use it without downloading python and setting up the whole thing.
if you don;t plan updating your bot ever i guess you might turn it into an exe
ik discord.ButtonStyle only shows these few colours but can we really not pass a discord.Colour to buttons? or even a hex code or something https://discordpy.readthedocs.io/en/master/interactions/api.html?highlight=discord buttonstyle#discord.ButtonStyle
No
The pitfalls of dynamically typed languages
that's a shame
well, blame discord for having just few button colors
I think they should really just allow us to input a custom colour

how do i make if they click a different option it returns something different
if Pickups == None:
pickups is none
if events == None:
events is none
``` etc etc
@hushed galleon how to send the game start message to both channels?
youd store both of the player's channels beforehand and then send to them when your game starts
hence why i mentioned considering storing it alongside the player as a (user, channel) tuple when they get queued
@narrow grail
thanks
Is there any apis for the welcome image?
Or should I use PIL to make it
Anyone here?
if i create a webhook via ```py
ss = session.create(f'https://discord.com/api/v9/channels/{channelid}/webhooks', headers=headers, json=json)
not 100% sry
I'm trying to make an on_message for a server of mine, where if there is no image attachment it deletes the message
but if there is, it keeps it
ex:
#screenshots (only images)
user says something, it deletes
user attaches image and says something, it stays
how would i delete a stage with py? (only works for someone with a certain role)
Hiho!
I've made a discord.py bot command:
@bot.command()
async def remind(ctx, *msg_parts):
...
and as you can see, I'm taking *args from the message. The problem is: when I put one quotation mark " in the message, I get an error: discord.ext.commands.errors.ExpectedClosingQuoteError: Expected closing "..
I have some idea why it's this way, but I don't have any idea about how to solve it. Could I get a hint? π
It's meant to be
async def my_command(ctx, *, arg_name):
...
Thank you a lot, I tried something similar before but didn't use it properly. Now it's working thanks to you! Thanks again! π
My pleasure!
Could you provide code?
how to i make it so when I do !promote then it give HC role then do !promote again then give GM role
HC = discord.utils.get(guild.roles, name="Head Coach")
await user.add_roles(HC)
This won't quite work;
First check if they have HC role, if so, give GM role (optionally remove HC role), if not, give them HC role
You're halfway there already
it gives them both roles
You're checking if they have HC role, but you don't have an else condition
if HC in user.roles:
# give GM role
else:
# give HC role
o
@client.event
async def on_message(msg):
if (msg.channel.name == 'screenshots'):
if not (msg.attachments) or ('https://cdn.discordapp.com/attachments/' in msg.content):
# delete message
Need help with this, I'm not that good at discord.py and wanted to see how I can delete a message that has no attachment on message.
You're on the right track, you only have to check msg.attachments truthy value
No need to check for the link
How would I do that?
Or should I remove msg.attachments and add if not ('https://cdn.discordapp.com/attachments/' in msg.content):
if not msg.attachments:
# delete
ah
Anyone know of any up to date alternatives to https://github.com/Ext-Creators/discord-ext-ipc? (ping on reply pls)
afaik there is none
@sick birch
I recieve this error
TypeError: 'in <string>' requires string as left operand, not list
@client.event
async def on_message(msg):
if (msg.channel.name == 'musa-moment'):
if not msg.attachments in msg.content:
await msg.delete()
no indent
hi pog π
ion know
Your indentation
You want to delete the message if there is not a attachment in it?
Yeah, I figured it out though.
Okay thanks
@client.listen()
async def on_message(msg):
if msg.channel.name == 'musa-moment' and not msg.attachments:
return await msg.delete()
Do I have to sanitize user input in commands that take keyword-only arguments? Like in !remind word1 word2: do I have to escape any characters or discord.py / python does it for me?
how would i use discord.ext.tasks.loop in this case
since after the first await it should sleep to the next like 10s
Message is repeating over and over again:
@client.event
async def on_message(msg):
if (msg.channel.name == 'π·βΏscreenshot-plane-spot'):
if not "https://cdn.discordapp.com/attachments/" in msg.content:
await msg.delete()
if ((" release" in msg.content) or ("release " in msg.content)):
await msg.reply("We are currently in a big development build up phase. Please check [#922607045969051698](/guild/267624335836053506/channel/922607045969051698/) for release information.")
await client.process_commands(msg)
but if i would do @tasks.loop(seconds=10) it would never get to the second part
@client.listen()
async def on_message(msg):
if (msg.channel.name == 'π·βΏscreenshot-plane-spot'):
if not "https://cdn.discordapp.com/attachments/" in msg.content:
await msg.delete()
if ((" release" in msg.content) or ("release " in msg.content)) and not msg.author.bot:
await msg.reply("We are currently in a big development build up phase. Please check [#922607045969051698](/guild/267624335836053506/channel/922607045969051698/) for release information.")
You still need the process command though
Thank you, I had this issue before I just forgot how to fix it.
How so?
can someone help
Sry idk
Object Orientated Programming.
No im asking for how to use it when it has a sleep function inside of it aswell
how would i make it add a reaction to the channels message. Check and X is defined at the begining of the code.
from discord import Game
from discord.ext import tasks
from discord.ext.commands import Cog, Bot
class Example(Cog, name='example_cog'):
def __init__(self, bot: Bot) -> None:
self.bot = bot
self.precences = [
"Hello!",
"Do a flip!"
]
self.loop_change_status_iteration = 0
self.change_status.start()
def cog_unload(self) -> None:
self.change_status.cancel()
@tasks.loop(seconds=10, reconnect=True)
async def change_status(self) -> None:
await self.bot.wait_until_ready()
await self.bot.change_presence(
status=discord.Status.idle,
activity=discord.Game(self.precences[self.loop_change_status_iteration])
)
self.loop_change_status_iteration += 1
if len(self.precences) == self.loop_change_status_iteration:
self.loop_change_status_iteration = 0
def setup(bot: Bot) -> None:
bot.add_cog(Example(bot))
Got it so it finished the task first before looping afterwards
So the sleep inside and the loop sleep dont effect each other
No?
I'm using a class to keep track of what iteration we're on.
If the amount of iterations is equal to the list reset to zero.
asign a variable to channel.send and use the add_reaction method on the variable
ss = requests.post(f'https://discord.com/api/v9/channels/{f}/webhooks', headers=headers, json=json)
```how would i go about returning the urkl of this webhook?
so i got a question
url = f"https://discord.com/api/v9/channels/{f}/webhooks"
will await member.unban() work? considering that the member object has already been banned?
That's the webhook URL isn't it? You're posting to it
if you store the banned member obj in a list for like, 10 mins, will .unban() unban them?
or no
Experiment
Yes if that is a valid member object.
alr
But you can get the snowflake from them either way
lets say, you store it for 3 years, will it still work?
It should, since you can easily get a snowflake from member objects
If your bot has run for that long and the api is the same why not.
This server is not meant for this.
sry
You could ask @novel apex if you can say it in some other channels.
k
im posting the request to create it
if you mean ctx.channel.create_webhook im not using it bc im trying to randomizew the channel. and d.pys method doesnt allow that'
Sure. Use random.choice()
ive defined f as a random choice of the channels.
but it comes up wit invalid type
Oh, then why not just use f.create_webhook(...)?
ss.url
hm.
returns the same thing
waift that actually does that?
Returns what? The error?
yea
It needs to be a channel object
whats he tryna do
If it's a list of IDs you can map or use list comps
Create a webhook in a random channel
Ah
list_of_ids = [123, 456, 789]
channel_objects = [bot.get_channel(id) for id in list_of_ids]
Or, preferably, if keep it as a list of channels from the start
or.. ```py
from random import choice
channel = choice(ctx.guild.text_channels)
Why would you import it then use random.choice()
ty
haha my mistake
AttributeError: 'list' object has no attribute 'create_webhook'
You have to use random.choice on it
hook = random.choice(channel_objects).create_webhook(name="xylo") like this?
hmmmm
or do i put thw whole thing in random.chice
Gotta await it but yes
yo @sick birch can u help me w sum rq
its still saying its a nonetype and doesnt have the atr create)_webhook
Is the list empty?
await stage1.set_permissions(ctx.guild.default_role, move_members=False)
await stage1.set_permissions(ctx.guild.default_role, mute_members=False)
only denying mute permissions & the move permissions are still neutral and gray
@sick birch
Can someone help me? Iβm having trouble changing the bots nickname. Iβm using v1.7.3
await client.user.edit(nick=βnickβ)```
am i doing something wrong
nope
(No error, just nothing happens)
Are you trying to change the bot's nickname for a server or it's username?
just the nickname (per server nick)
@magic ore mind helping w that
property me```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
has an edit method
So then discord.Guild.me.edit?
Is ylo a packing clan
no
you would access the me attribute of a Guild object (or Context object) and call the edit method on it
!d discord.Member.edit
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the memberβs data.
Depending on the parameter passed, this requires different permissions listed below...
ye ylo is ass ngl
ah ok, thanks
@magic ore yo? u mind helping me
await stage1.set_permissions(ctx.guild.default_role, move_members=False)
await stage1.set_permissions(ctx.guild.default_role, mute_members=False)
only denying mute permissions & the move permissions are still neutral and gray
looks fine to me, make sure your bot has the right permissions
it does
i can inv u to my test serv
and give u admin perms idk why it isnt
working
its for a stage channel so idk if that shit works differently
@magic ore its resetting the move member permission as it does it idk why
nvm i found out y
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
client = MyClient()
client.run('Token you though u were gonna get that L')```
okay
what's the problem
Is this good so far this is my first project I started on so far and I need some feedback from this is there anything I need to improve on it?
i suggest using commands.Bot
it inherits from discord.Client so it has all of it's features with more
like commands so you don't have to make a bunch of if statements checking if a message has your prefix and command name
first project?
yea
like your first python project?
yes
damn good luck
Thanks I like taking a challenge because I am wanting to learn from this.
Hi! This is my first time making a discord bot using python
`@commands.command()
async def play(self,ctx,url):
ctx.voice_client.stop()
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
YDL_OPTIONS = {'format':"bestaudio"}
vc = ctx.voice_client
await ctx.send("Playing!")
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info['formats'] [0] ['url']
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
vc.play(source)`
So i'm making a discord music bot here, but when i want to play something i get this error
How would I re write it to the way you said you recommend it to be?
can't help
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeβs robots.txt file; (b) with YouTubeβs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
replit doesn't support ffmpeg anymore
use f-strings
@client.event
async def on_message(message):
try:
if message.author.bot:
return
for attch in message.attachments:
if (
attch.filename[-4:] in ['.jpg', '.png', '.jpeg']
and str(message.channel.id) == str(959954871656796223)
):
user_points = get_config("points")
user = message.author
key = f"{user.name}#{user.discriminator}"
user_points[key] = user_points.get(key, 0) + 1
save_config("points", user_points)
finally:
# let other commands run
await client.process_commands(message)
wondering how I can make it send an embed whilst replying to the user who sent the image
want it to reply to the image with this
!d discord.Message.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").
New in version 1.6.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
yes I know that, but im confused where I'd put my embed and stuff
await message.reply(embed=embed)
no like literally my embed contents, where would I put them without messing up the rest
what
put them inside a embed then
why do you have a try and finally
for the await client.process_commands(message)
but why do you have a try block
for what actual reason do you have that there for
someone suggested using it a longgg time ago
πΏ
?
bruh
it has been working good though
yeah it works but you don't need try and finally
literally no reason to use them
you're not even catching errors with an except block
because up until now I didn't need to
can you help or are you gonna criticize all of it π€£
you don't need finally just remove it
and put the process_commands on the first level
Which line
How can you check if message.content contains something?
if message.content == "something":
...
or
No like if it starts with &
if '&' in message.content:
if message.content.startswith("&"):
...
or that yeah
he wanted startswith
ah gotcha
just put the embed in your last if statement
you want me to move await client.process_commands(message) on the same level as save_config?
def foo(bar: Bool) -> Str:
# first level
if bar:
# second level
return "second level"
else:
return "example"
yes
it has to be the same indentation line like the first if statement
but on the last line
or just use bot.listen
4th line is the first if statement
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
@client.listen() ?
you don't have to process commands with this
yes but i hate that variable name
because your bot is a bot
not a client
also confusing because discord.Client exists
can someone help me with this?
@commands.command()
@commands.has_permissions(administrator=True)
async def unban(self,ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.channel.send(f"Unbanned: {user.mention}")
it's like doing this
you didnt provide a reason
youre not passing in enough values
string = 1
number = "my string"
@austere vale why do you have *, ?
is * not needed?
- is all isn't it?
yeah but why would she need that?
same as ColdLuck#6969
yea
it wont be ColdLuck # 6969 where you need to see all those words
even if you did, with your code it causes errors
thank HAHA
@supple thorn what do I set as the name for the .listen and what does it matter?
How do I check the message.channel.id?
what
str(message.channel.id) == str(channel ID)
no
thats what I use
So it should be if message.channel.id == id:
yeah works but can be better
Right?
yeah
ye
i don't know why he turns them into a string
make sure id is an int
Well it should be
???
useless to turn them into a string when they are both already a int
allows you to have multiple of the same event
so does the name matter?
@bot.listen("on_message")
async def quack_messages(message):
...
if you want to have multiple events
then yes
if no
In my case for detecting on message does it matter
just don't put anything for the name
@bot.listen()
async def on_message(message):
...
how do i fix this?
@commands.command()
@commands.has_permissions(administrator=True)
async def unban(self,ctx, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.channel.send(f"Unbanned: {user.mention}")
why are you passing in a reason with no argument
can you get rid of your error handler and send the error here
also dont copy and paste code, this is why you're running into errors and dont know how to fix it
- It needs to be name#1234 2. U can use id mention etc by using
discord.Usertypehint andctx.guild.unban
The way ur using is bad
copy pasting code...
attch.filename[-4:] in ['.jpg', '.png', '.jpeg']
NameError: name 'attch' is not defined
i define it above though idek
show code
you don't have it defined then?
how dont u know lol
Anyone here know how to host a bot using railway?
I'm having issues
I'm trying to host the bot but it fails during the build
railway?
Yes
no idea I would just recommend buying a $2 vps
I have all my bot code in a repo but it's seperated by folders in the repo per bot
or even heroku i think is simpler
I don't have $2
Doesn't have unlimited time
i think thats more of a railway problem then a discord.py problem..
i have 2 questions one is how do i for example like i have a prefix command that saves the guild id and prefix to a json and i want to like reply with that set prefix when i mention the bot how do i extract the prefix again? and other question is how would i do like categories in a help cmd embed like dank memer
like this
what error you get?
ah i got it
you don't have reason argument in function
so you can't give reason for unban
include that first
will that work with dpy 1.7.3
if i use 2.0 will my commands ect go to waste like be unusable and ill have to use the new 2.0 lib and docs to make my bot again?
there are a few breaking changes but mostly everything will work all good
okay ill try, worst case ill have to get back to 1.7.3
good luck
and how would i ctx.send the set prefix for the current guild the bot is in
- get the prefix using this
- send it
!d discord.ext.commands.Bot.get_prefix
await get_prefix(message, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the prefix the bot is listening to with the message as a context.
Changed in version 2.0: `message` parameter is now positional-only.
its python 3.8 or higher
so 3.10 works
okay ty
is there any way to get the id of a previous message in a specific channel? like i need the id for the second to most recent message, not just the most recent one
i know await channel.history(limit=2).flatten() can get me a list that contains the id, but i dont know how to 'extract' it per say
use just 1 bot instance
did you import discord?
what exactly is the error
i'm not sure then, maybe someone else will know
@slate swan ive installed 2.0 and added the intents and now none of my cmds are working did i do anything wrong because im not getting any errors has anything else exceptionally in my case what im having a problem with changed?
maybe its cuz of my custom prefix line
perhaps
try removing that for now
and just put a test prefix in it's place
client = command.Bot(command_prefix= get_prefix, intents=intents)
is that correct
sure
what
no clue cause i don't use discord py 2.0
not even discordpy
i use disnake
what's your get_prefix code
def get_prefix(client,message):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
client = command.Bot(command_prefix= get_prefix, intents=intents)```
how can I make an error handler specifically for CommandInvokeError
@plb.error
async def plb_error(ctx, error):
if isinstance(error, commands.CommandInvokeError):
await ctx.send("No users have points!")
is that incorrect?
it's commands.Bot
Did u enable message content intents?
yeah it probably is because of this
All intents enabled
The bot is intended to get verified
it can't work without defining bot correctly
jesus christ
you realize @ here will ping all members right
yes
Its a nsfw bot and i have a server thats growing like hundreds of members daily cuz of the server and the bot is just an addition to the community and i also thought why not be public for everyone
why else would he put a here ping
?
Especially since kinks and stuff exist and searching for nsfw in a public server with kinks is a bit weird
yes im about to annoy people
ahh gotcha :demon:
did you fix what we told you though
No it didnt
what did u do
wtf ppl are discussing lmfaoo
demon's weird kink bot that uses client
Yea
Lols
oo ok ok.. i got wrong idea by reading that 'kink' word
lmfao (everything cool nwo lol)
ahh.. listen.. try to not use json for that shit
if possible

Why
With a get prefix which opens a json file every time
json aren't meant to be used as db
if u wanna use db.. u can use free plan of mongodb
do you have an error?
Ok enough talking about my mommy bot
No error just all cmds are not working
how are you gonna use a db as a config file tho
Show intents
on_message?
or sql one
π bro, so u saying that one should use json to store prefix?
bro
Messages is not message content I think
why do you have client
i'm saying you shouldn't tell them to use mongodb as config file π
yeahh i've heard that pythonanywhere gives free 500mb of mysql
π oh i see, lmfao
that's why
i just intent to tell ppl to not use json for that shit :'/
bruh
of course you are
What difference does it make in 2.0
Use only the commands.Bot
+1 ^
So no client
Yes
why are you defining client twice?
Just use commands.Bot
Yes
how the fuck did your old code work
use a yaml file if you want smthn like that 
No idea
and what do i do with the prefix
It does tho
or a toml file
Im testing the bot on a different application and the main bot is running on my pi with the default version
your code challenges the holy spirit
May jesus help
π
You need to set intents.message_content to True
if the code works don't touch it
- some random guy
Me
So yh what do i do with
Here
are you trying to do a prefix for every server or a prefix by default?
Prefix for every server
Its already in like 40
Should use bot vars and only open file on start and close
π that's why i'm telling to not use json for that
intents = discord.Intents(messages=True, guilds=True)
Shouldnt this be enough
No
messages is not message_content
everyone is trying to help demon but it ain't working 
Im sorry im dumb sometimes
π
I sincerly apologize and appriciate your love and help.
btw which lib you're using? @lucid vine
Dpy2
intents = discord.Intents(message_content=True, messages=True, guilds=True)
commands.Bot = discord.Client(intents=intents, command_prefix= get_prefix)
# ================================================================================================================
def get_prefix(client,message):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
client = command.Bot(command_prefix= get_prefix, intents=intents)```
so i know i did something wrong
Just not sure what
i don't even know how their code lives
Remove commands.Bot = discord.Client
Its a supreme AI it fixes itself
π ai?
Im joking
Yh then
π i thought u talking about copilot lmfao
idk if this helps but :\ https://stackoverflow.com/questions/64513680/discord-py-prefix-command
and he using json for that shit..
that's why i told him to not use json for that shit
let them experience it
lmfaooo
intents = discord.Intents(message_content=True, messages=True, guilds=True)
# ================================================================================================================
def get_prefix(client,message):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
client = command.Bot(intents=intents, command_prefix= get_prefix)```
No clue what im supposed to expierence
π
Is it at least working now?
Fuk i forgot the commands
see.. just telling that json isn't meant to be used as what you're tryna use it for
bie
damn
Whats wrong with it i dont know it works i
bro
All about the rules and common practices for coding a Discord bot
Json is a data serialization format, that turns primitive data structures into a string.
A database is a formalized system designed to store and retrieve data, with a substantial
number of features and functionalities designed to support doing so at various scales,
and with a large number of guarantees.
A Json file as-a-db* is fundamentally flawed due to its lack of atomic writes
which results in data corruption and loss when:
β’ The disk runs out of storage
β’ The program crashes during the write
β’ The computer crashes during write
β’ Two programs try to write to the file at the same time
Additionally:
β£ All reads require the entire file to be read
β£ All reads require the entire structure to be loaded into memory *this does make it fast!
β£ All writes require the entire file to be re-written
The Json module makes no effort to ameliorate any of these concerns, because json-as-a-db falls
completely and entirely out of the scope of the standard.
If you need the file to be portable and want minimum setup, use sqlite, a standard designed to
solve all these issues.
*Using the json stdlib module
it is used for configuration not to be used as a db
Nope not working
No errors?
No errors just not working
Did u enable intents in dev portal
u aren't getting any error even you're running the file? π
Just double checked
why not use FASTAPI aswell π€£
bruhh
Can u maybe show more code
^
What do u need
Maybe a few commands, where ur running the bot
!paste or a whole file
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Yh i can give u a snippet 2 sec
:incoming_envelope: :ok_hand: applied mute to @lucid vine until <t:1649310216:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 112 newlines in 10s).
π
lmao
LMFAOOO
Lol
hey mod, pls unmute him
wait for another 10 minutes
Use this for large code next time
Ok so loading extensions needs to be awaited
Also u shouldnβt change status so often
Probably
on a sb i would understand but on a bot?
Ok so you should make an async function named setup_hook where u load extensions. Then do client.setup_hook = setup_hook. Make sure to await loading extensions
Oh
its messy code
Well ur also not running the bot
Oh ok
didnt send full code
Page not found
Ok
what do i need to type in my terminal to be able to use attribute "create_Text_channel ?
wtf timeout is finished but im still muted
is ctx.author in a slash command the bot or the user who ran the command?
I would assume user
how to use twitch api?
@bot.command()
async def stopwatch(ctx, status : int):
hours = 0
minutes = 0
seconds = 0
if status == 1:
await ctx.send("Started")
while True:
time.sleep(1)
seconds += 1
if (seconds == 60):
seconds = 0
minutes += 1
if (minutes == 60):
minutes = 0
hours += 1
if (hours == 24):
hours = 0
minutes = 0
seconds = 0
break
elif status == 0:
break
elif status == 0:
await ctx.send("Stopped")
I get no error but the bot doesn't send a message when i stop
what is status
also that's really bad to do cause that is blocking
pretty much making your entire bot seize up until it finishes that code
because it already started
ok i think i got it
I am sorry but.. what do you want this to accomplish?
counting i presume
why is one of your arguments discord.Channel
thats not my question
its a stopwatch
File "C:\Python310\lib\site-packages\discord_components\component.py", line 3, in <module>
from discord import PartialEmoji, Emoji, InvalidArgument
ImportError: cannot import name 'InvalidArgument' from 'discord' (C:\Python310\lib\site-packages\discord\__init__.py)
but that will be later when it fucks you over
Because you have (ctx, channel, discord.Channel) and not (ctx, channel: discord.Channel).
Can someone help
thanks, finnaly someone with usefull help
isn't it from commands
what d.py version are you using?
You should use asyncio.sleep() for the whole duration. Do you want it to send a message every now and then about the remaining time?
2
Wym
looks like a library error
literally pointed it out yet said no
πΏ
no, i want to see the time elapsed only after i stop it
So what do i do
CokeCane is correct, you want to import it from discord.ext.commands: ```python
from discord import PartialEmoji, Emoji
from discord.ext.commands import InvalidArgument
don't mind that just looked at the docs
How do you stop it? With another command?
i was right?
i'm looking at the docs
No
i don't see invalidargument from commands
But im trying to use dropdown menu as category for help command
hi is the python bot open source ?
In embeds
yes
!github
!source
Yes! It's a bit more complicated than usual bots so I recommend looking at @lament depot unless there is a specific feature of Python bot you want to look at.
π will check out both
it's using disnake
It was migrated back!
what
you can do that with discord.py too
oh, nice
didn't it migrate back
v2.0 is not out yet right ?
it's been out for a while
yeah i looked at it's src couple days ago
Like lets say someone does _help and then it does a embed and then adds a dropdown with like 3 categories like moderator, fun, level and once u pick one it will give u a help embed with the multiple commands in that category in a embed
That ^^
huh i think only beta version is out not a stable version
I never knew about InvalidArgument; the thing is, that's not the one raised by converters afaik
It did yeah
eyyy
it's a beta version but is pretty much stable, not much bugs which will break your bot
i see
have you guys used hikari.py for making bots ?
nope but i would try it out soon
nah
i see , pls tell me how is it after you try it out
maybe looking at https://github.com/Rapptz/discord.py/blob/master/examples/views/dropdown.py will help with what you wanna do
BTW do you guys have any ideas what is the rest api and gateway version of discord currently ?
v10 is the latest gateway version
Ignoring exception in command colour:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 192, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Yuki\Desktop\KyuuMainPy\r34bot\main.py", line 556, in colour
await ctx.send.embedhelp(view=view)
AttributeError: 'function' object has no attribute 'embedhelp'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1234, in invoke
await ctx.command.invoke(ctx)
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 932, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 201, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'function' object has no attribute 'embedhelp'
error
embedhelp = discord.Embed(title="Mommy's Help Menu", color=0xff80ff)
embedhelp.add_field(name="'r34 [tags]'", value="**NSFW** Polls rule34 accordingly to your tags.", inline=False)
embedhelp.add_field(name="'prefix'", value="Changes your GUILDS set Prefix for Mommy", inline=False)
embedhelp.add_field(name="'coin'", value="Flips a coin.", inline=False)
embedhelp.add_field(name="'kill'", value="Kills a User.", inline=False)
embedhelp.add_field(name="'hug'", value="Hugs a User.", inline=False)
embedhelp.add_field(name="'kiss'", value="Kisses a User.", inline=False)
embedhelp.add_field(name="'sex'", value="**NSFW** Makes out with a User.", inline=False)
embedhelp.add_field(name="'kick'", value="Kicks a User. : _kick @user", inline=False)
embedhelp.add_field(name="'ban'", value="Bans a User. : _ban @user", inline=False)
embedhelp.add_field(name="'mute'", value="Mutes a User: _mute @user.", inline=False)
embedhelp.add_field(name="'unmute'", value="Unmutes a Muted User. : _unmute @user", inline=False)
embedhelp.add_field(name="'tempmute / tm'", value="Temporarily Mutes a User : _tm @user 10s/d/w/mo/y tempmutereasonhere.", inline=False)
embedhelp.add_field(name="'userinfo'", value="Returns information about the User!", inline=False)
embedhelp.add_field(name="'serverinfo'", value="Returns information about the Server!", inline=False)
embedhelp.add_field(name="'rr'", value="**NSFW** Russian roulette. Posts gore images if gun goes off.", inline=False)
embedhelp.add_field(name="'shibe'", value="Posts an image of a Shiba inu.", inline=False)
embedhelp.add_field(name="'cat'", value="Posts an image of a cat.", inline=False)
embedhelp.add_field(name="'bird'", value="Posts an image of a bird.", inline=False)
class Dropdown(discord.ui.Select):
def __init__(self):
# Set the options that will be presented inside the dropdown
options = [
discord.SelectOption(label='Red', description='Your favourite colour is red', emoji='π₯'),
discord.SelectOption(label='Green', description='Your favourite colour is green', emoji='π©'),
discord.SelectOption(label='Blue', description='Your favourite colour is blue', emoji='π¦'),
]
# The placeholder is what will be shown when no option is chosen
# The min and max values indicate we can only pick one of the three options
# The options parameter defines the dropdown options. We defined this above
super().__init__(placeholder='Choose your favourite colour...', min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
# Use the interaction object to send a response message containing
# the user's favourite colour or choice. The self object refers to the```
code
Morning guys
Use id
Hello blvck
<:emoji_name:emoji_id>
That does not work apparently.
i made a fiverr account
don't know what to do though
await ctx.send(embed = embed, view = view)
yes
Does all welcome commands need a db?
async def callback(self, interaction: discord.Interaction):
# Use the interaction object to send a response message containing
# the user's favourite colour or choice. The self object refers to the
# Select object, and the values attribute gets a list of the user's
# selected options. We only want the first one.
await interaction.response.send_message(f'Your favourite colour is {self.values[0]}```
how do i set this to a custom embed depending on the interaction object?
Instead of the your favourite colour is ...
you can make a single welcome message which will be send in every server, but it sucks 
Doesn't work.
Because that emoji is not in your guild
hey a question, how to make sub commands NOT case sensetive?
Use it like this to get the emoji id ect \ (emojihere), no space
I think u could make the caps equal to lower caps
wdym?
Like setting the caps to lower caps wait i knew how to but i forgot
Let me check
then can u tell me how to
k
!lower()
ye but a sub command
set the case_insensitive kwarg in the group decorator to True
if statements I suppose ```py
if self.values[0] == 'fun':
...
elif self.values[0] == 'moderation':
...
But like
?
Oh like that
I see ty let me try
1
What?
You have to use the emoji id
The emojis have to be in the bots guild tho
!d discord.Client.get_emoji
get_emoji(id, /)```
Returns an emoji with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
This is more correct method
you're not
Then what did i do wrong
your just using tabs and spaces together and python doesn't like that
I didnt i just used tabs
π€
I cant run my code like this
@lucid vine in vsc in the bottom right corner there's something that let's you convert code to tabs/spaces so you can quickly fix it
Typically pressing tab in VSC results in 4 spaces added as PEP8 states indents are recommended to be implemented with 4 spaces
If you didn't change the settings
I see ty i just removed the tabs and used space instead
class Dropdown(discord.ui.Select):
def __init__(self):
# Set the options that will be presented inside the dropdown
options = [
discord.SelectOption(label='NSFW', description='NSFW commands', emoji='π'),
discord.SelectOption(label='Fun', description='Fun commands', emoji='π'),
discord.SelectOption(label='Mod', description='Moderation commands', emoji='π§'),
]
# The placeholder is what will be shown when no option is chosen
# The min and max values indicate we can only pick one of the three options
# The options parameter defines the dropdown options. We defined this above
super().__init__(placeholder='Pick your Category...', min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
# Use the interaction object to send a response message containing
# the user's favourite colour or choice. The self object refers to the
# Select object, and the values attribute gets a list of the user's
# selected options. We only want the first one.
if self.values[0] == 'NSFW':
await interaction.response.send_message(embed=embednsfw)
elif self.values[0] == 'Mod':
await interaction.response.send_message(embed=embedmod)
elif self.values[0] == 'Fun':
await interaction.response.send_message(embed=embedfun)
class DropdownView(discord.ui.View):
def __init__(self):
super().__init__()
# Adds the dropdown to our view object.
self.add_item(Dropdown())
@client.command()
async def colour(ctx):
"""Sends a message with our dropdown containing colours"""
# Create the view containing our dropdown
view = DropdownView()
# Sending a message containing our view
await ctx.send(embed = embedhelp,view=view)
how would i make this after ive selected the dropdown category the initial embed deletes itself
message = await ctx.send(embed = embedhelp, view=view)
when you want to delete it:
message.delete()
or you can even edit it:
message.edit(embed=a_new_embed)
So how would i edit my await ctx.send(embed = embedhelp,view=view) to the new embed

So how would i make it that when the interaction response gets sent it gets deleted
Im confused
bro when you response to your interaction you send a new embed, right?
Yea
essentially you can do it in a lot of different ways:
saving the id of the message you want to delete, then use your interaction in the view to access that message and then delete it.
create a message parametere in your UI view and then you first send the message with the embed, then you create the view object, pass the message that you have sent, and then edit the message to add your view and then when the interaction is responded before sending the new embed delete the old one
is up to you
Can i just define the initial embed and then like add it to my if .... elif ... and delete it then?@placid skiff
Or wont it work like that
nope the embed is in the message, so you have to remove it from the message or delete the entire message
why not edit it
Cuz i have no idea
await interaction.response.edit_message(embed=...)
class Dropdown(discord.ui.Select):
def __init__(self):
# Set the options that will be presented inside the dropdown
options = [
discord.SelectOption(label='NSFW', description='NSFW commands', emoji='π'),
discord.SelectOption(label='Fun', description='Fun commands', emoji='π'),
discord.SelectOption(label='Mod', description='Moderation commands', emoji='π§'),
]
# The placeholder is what will be shown when no option is chosen
# The min and max values indicate we can only pick one of the three options
# The options parameter defines the dropdown options. We defined this above
super().__init__(placeholder='Pick your Category...', min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
# Use the interaction object to send a response message containing
# the user's favourite colour or choice. The self object refers to the
# Select object, and the values attribute gets a list of the user's
# selected options. We only want the first one.
if self.values[0] == 'NSFW':
await interaction.response.send_message(embed=embednsfw)
elif self.values[0] == 'Mod':
await interaction.response.send_message(embed=embedmod)
elif self.values[0] == 'Fun':
await interaction.response.send_message(embed=embedfun)
class DropdownView(discord.ui.View):
def __init__(self):
super().__init__()
# Adds the dropdown to our view object.
self.add_item(Dropdown())
@client.command()
async def help(ctx):
"""Sends a message with our dropdown containing colours"""
# Create the view containing our dropdown
view = DropdownView()
# Sending a message containing our view
await ctx.send(embed = embedhelp,view=view)
Will it know to edit the initial embed?
if you mean embedhelp then yes
what form do i need to open an image in to use await client.user.edit(avatar=image)? i tried rb and r and image.read() but none of that works. this is my code:
with open(f'pfps/' + str(math.floor(random.uniform(1, 8))) + '.png', 'rb') as image:
image.read()
await client.user.edit(avatar=image)
hi! i am using async-praw for a discord bot as praw is blocking. does anybody know any help servers like this for it?
i am encountering an authentication error when my credentials are correct.
I don't think they have a discord server
aw
understood, thank you
my question has been asked multiple times there.
lmao
i tried all those fixes, none of them seem to work
i'll just claim a help channel
@client.command()
async def clear(ctx, amount=1000):
await ctx.channel.purge(limit=amount)
await ctx.send('Successfully delete {amount} messages')
```How can i fix the `{amount}`? I want it to send a specific number
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
Oh thx
you should actually store the purge method in a variable and use the len function on it since purge returns a list of Message objects, it will tell you the number of messages deleted rather than simply using the amount set by the user who invoked the command
Yeah,it can fail to delete messages so if you say it deleted what the user put in it's inaccurate or misleading
Consider typehinting amount to int also
!d discord.TextChannel.purge
hello Ashley
!e import random
def highlow(num, high):
counter = 0
computer_guess = random.randint(1, high + 1)
already_there = []
while computer_guess != num:
if num not in range(1, high + 1):
print("Dirty bastard... I know what you've done. You cannot fool this machine.")
break
already_there.append(computer_guess)
if computer_guess not in already_there:
counter += 1
computer_guess = random.randint(1, high + 1)
print("A.I is computing", computer_guess)
print("... \n ... \n ...")
if computer_guess == num:
counter += 1
print("Algorithim correct! I will rule mankind! It only took", counter, "tries!")
highlow(12, 12)
!e import random
def highlow(num, high):
counter = 0
computer_guess = random.randint(1, high + 1)
already_there = []
while computer_guess != num:
if num not in range(1, high + 1):
print("Dirty bastard... I know what you've done. You cannot fool this machine.")
break
counter += 1
computer_guess = random.randint(1, high + 1)
print("A.I is computing", computer_guess)
print("... \n ... \n ...")
if computer_guess == num:
counter += 1
print("Algorithim correct! I will rule mankind! It only took", counter, "tries!")
highlow(12, 12)
@fallen merlin :white_check_mark: Your eval job has completed with return code 0.
Algorithim correct! I will rule mankind! It only took 1 tries!
!d discord.Embed.set_author
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Well you can't pass set_author into ctx.send.
!e import random
def highlow(num, high):
counter = 0
computer_guess = random.randint(1, high + 1)
already_there = []
while computer_guess != num:
if num not in range(1, high + 1):
print("Dirty bastard... I know what you've done. You cannot fool this machine.")
break
counter += 1
computer_guess = random.randint(1, high + 1)
print("A.I is computing", computer_guess)
print("... \n ... \n ...")
if computer_guess == num:
counter += 1
print("Algorithim correct! I will rule mankind! It only took", counter, "tries!")
highlow(12, 12)
@fallen merlin :white_check_mark: Your eval job has completed with return code 0.
001 | A.I is computing 7
002 | ...
003 | ...
004 | ...
005 | A.I is computing 7
006 | ...
007 | ...
008 | ...
009 | A.I is computing 9
010 | ...
011 | ...
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/puyujuqeme.txt?noredirect
πΏ
i can see that
#bot-commands
#bot-commands
oh whoops
Yeah, you need to do```py
embed = discord.Embed(...)
embed.set_author(...)
await ctx.send(embed = embed)
πΏ
but i don't want that
But you need that
if i were to embed these all, will that method still work?
very messy code here
i just said that i plan on embedding it all
He's referring to the if statement
yes
Also, instead of doing two if statements for the RPS, you could just use an and.
i'm gonna add them in the same embed
Is there any alertnative for in method to send message faster via discord webhooks!
You want to send messaged using webhooks rather than the normal way?
Yes i have stored webhooks!
