#discord-bots
1 messages · Page 79 of 1
this code totally fails lmao,
what if the message has 2 items from the words list in it
you can't delete the same.message twice
He made it lower
!e
bad_words = ["bad", "naughty"]
input_ = "BaD"
if input_.lower() in bad_words:
print("Yes >:(")
@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.
Yes >:(
I don't understand what you're saying
where do i put the check, do i put it in the command and check to see if the value still equals the default value?
nvm found out
With an if statement that is so
if not value:
...
I mostly want to be able to return a message if they give something that is not a channel bit something else entirely like a number
Well then you wouls probably need to catch a conversion error which i forgot which one exactly
try it and see!
are the filtered words all lowercased?
why this one gives me an error
if isinstance("MissingAnyRole", (commands.MissingRole, commands.MissingAnyRole)):
await ctx.send("you dont have the role")
?
wait ik the error
that works only in python 3.10 iirc
also, this will never be true, why are you comparing a string with those objects in instance
i had the error instead of the first ins
im trying to except the missinganyrole error
to send a reply message
how was i not clear with the python version thing, that will work only and only in python 3.10+
are you on that version?
what is wrong with this code?
whenever I print the event content it just puts "none" in the terminal
Reset your token
Its probably an intent issue
MTAxNzQ3MjE50TQyNDIyOTQz0A.GpjYj1.0oq9w7GgZNhR8Xj2vWn_UmwAn2MRw9IM2N4rH8
hopefully it resets it automatically
yeah ik
its a test boty
because calling fetch_member will return a coroutine, which then needs to be awaited
Coroutine*.It Returns a coroutine upon the calling of the function to be specific
ok god
thanks
yes... that's what I said
Your wording was far from it
literally the exact same wording but ok
No?
It Returns a coroutine upon the calling of the function
because calling
fetch_memberwill return a coroutine
(edited) 
what are intents
yeah, I was correcting my spelling of coroutine
and where do I put it
!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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.
ah thanks!
ok
whats wrong with this?
I can still read your token
but what is wrong with it?
so uh i'm getting a 403 even though the bot has admin perms in my server and intents is Intents.all()?
Can you send the whole error?
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
pretty standard stuff
What line is it happening on in the traceback?
it runs and instantly stops
ik
role = discord.utils.get(server.roles, name="test")
member = await server.fetch_member(user.id)
print(dir(member))
await member.add_roles(role)
```the 4th one
you
then line where you cann .run is inside of your function, so it won't get called unless that function is called
OH FUCK I DIDNT SEE THAT
Dont leak any part of your token, especially the most important part, Your run method is inside of a function and youre missing the message content intent and use if member is None:
im refreshing it after
lmao
Is the role you are trying to add above any role your bot has? bots can only add roles that are below it in the hierarchy of roles
my bot has admin, and it's just a member role?
?
the token, its a test bot anyway
but is it? having admin doesn't matter, it can't add roles to members if the role is above the bot's highest role
Should use an env file to avoid hijacks and possible attacks with your bot
isn't having admin the highest role?
since that looks like replit, I would definitely suggesting using secrets
Does secrets have cryptography? Not exactly sure why you recommended it
having administrator is a permission. for example, here's a server where I have a mod role with administrator. But I can't give myself the admin role because it's above my role
I imported it over from my vis studio code
I wanted to see if it was just a visual stud problem
wtf does this mean
more intents stuff!!!!
make sure you've enabled the intents you need in the dev portal
...
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.
https://discord.com/developers/applications
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
oh it worked
I havent coded discord.py in like 3 years I didnt know what intents were 💀
yeah, the kwarg just became required with 2.0
?
ok i added a mod role to the bot
still doesn't work?
Is it still the same 403 error?
yeah
try going into role settings and explicitly enabling the manage roles permission
if you create a class instance and put it in a dictionary dict["something"] = class(values) and then make a reference to it reference = dict["something"] and then do del dict["something"] are you also deleting reference
not quite the right channel tbh
how do i make the bot detect who used the slash command
Only the value in the dict gets deleted but reference still points to its value
If you're using discord.py, and some forks are similar, interaction.user
!d discord.Interaction.user
The user or member that sent the interaction.
i had a feeling that would work but i just didnt bother trying lol
im using discord not discord.py is that diferent like it doesnt use ctx ns tuff
!d
?
!e
class banana:
def __init__(self, bob):
self.bob = bob
butt = {}
butt["something"] = banana("test")
jeff = butt["something"]
del butt["something"]
try:
print(jeff)
except:
print("no longer exists")
@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.
<__main__.banana object at 0x7fd60b8af950>
i use import discord and not import discord.py
channel = embed=discord.Embed(title="Logs Messages", description=f"Message de {message.author} {message.content}")
await message.channel.send(embed=embed)
channel = client.get_channel(1017579623552405554)```
Hi, I would like the {message.author} not to be repeated (it's for a "Logs Messages" discord room
the namespace of the package, or what you import from, isn't what determines what package you're using (noid don't correct me I know my wording is a little weird here)
oh ok
if you just did pip install discord, you're probably using discord.py
and?
Yep it still points to that value, sorry if confused you as i got confused with other languages memory management
huh
Please help me
oh boy, another replit being ratelimited
why so
for some reason i was questioning whether it was different with class instances
F 
commands not working
Oh no, do remember you mostly add values that are instances e.g 1 i can relate tho sometimes i question things like that, that obviously work
replits run on shared machines. So your bot is running on a computer that is shared with other people's replits, which might also be running discord bots, on a shared IP address. So if too many requests come from that computer, or someone decides to abuse the api or ratelimits from a replit that just happens to be on that machine, it'll get blocked, which blocks every replit running on that computer.
@wicked atlas do you know the problem here?
Set intents.messages to true
You mean containers? I'm pretty sure they arent the same
intents.message_content
any way to fix? and also will that cuase my bot to break a few hours after i started thec ode
Mb
channel = embed=discord.Embed(title="Logs Messages", description=f"Message de {message.author} {message.content}")
await message.channel.send(embed=embed)
channel = client.get_channel(1017579623552405554)```
Hi, I would like the {message.author} not to be repeated (it's for a "Logs Messages" discord room, HELP ME PLEASE.
?
I'm calling it a replit because that's what they like to call em sometimes
What are you trying to do
I don't understand
This and the paragraph i mentioned are both confusing me due to wording
Best, long term solution: don't use replit, get an actual VPS to host your bot
More tedious, and annoying solution: wait until your replit gets put on another machine or the machine it's on gets unblocked
This is a message log for my discord server (But the messages are repeated many times)
yup
i remember i used to be able to keep bots up for months at a time tho
so thers no way to fix while using rpl?
It's usually pretty random, and I think there's been a bit of an increase in people trying to host bots on replit
especially since heroku just announced the end of their free plan
you have an extra S in there
it's not that expensive to buy hosting
oh kek
like half of the price of an amazon subscription
I love how discord recommends their platform and dont specify its only good for HTTP only applications
also what do theese do
im dumb srry
hosts a server for your bot so you can ping a server to keep it up
I think
Well, they're recommending it now because of HTTP app commands
like the host and port variables
Can you show the full code for that
I'm pretty sure they recommended it before the whole slash command and message content intent update
well then that's pretty odd
what does WARNING: This is a development server. Do not use it in a production deployment. this mean
Python discord bot
The way the "keepalive" strategy works on replit is by running a webserver alongside your bot, then using another application like UptimeRobot to ping that webserver, which makes replit think that the site is getting activity, and thus keeps your application running
async def on_message(self, message):
channel = embed=discord.Embed(title="Logs Messages", description=f"Message de {message.author} {message.content}")
await message.channel.send(embed=embed)
channel = client.get_channel(1017579623552405554)```
i ues uptimerobot but wahts the warning for
Oh boy
Uh yes ?....
That message is a warning message from the webserver you're trying to run, which is probably flask. The run() method of a flask app isn't meant to be used for a production app, usually you should use something like uvicorn to run it.
So it will stillwrokpriperly?
ehhh, it'll work as long as the IP you're on dosen't get blocked
still, wouldn't suggest using replit as a hosting service, at least the free tier
So, you're trying to log the message by sending the embed to the channel where the message was sent, and the message that your bot sent will also be logged, and it keeps looping
Yes it is, and I wish it wasn't.
Then let's fix that
if message.author == client.user:
return
?
@naive briar
It repeats it to me in loop
You can put that on top of the log function to check if the message author is your bot or not. If it is, then don't log it
I want the bot messages to be ignored
Then just add the check to it
async def on_message(self, message):
if message.author.id == bot.user.id:
return
embed = discord.Embed(title="Logs Messages", description=f"Message de {message.author} {message.content}")
await message.channel.send(embed=embed)
channel = client.get_channel(1017579623552405554)```
thx bro
Error in the "bot" level 👀
I'm thinking its because you used bot, but they're using client
I am a beginner in python so I must confess that I do not understand your question
So no
It appears that you have self in the on_message function
Are you subclassing the bot? Like
class MyBot(Bot):
...
no class MyClient
hosting a bot online 3$ is the cheapest option?
Right
thats not cheap 😄
You can simply replace bot with self
async def on_message(self, message):
if message.author.id == self.user.id:
return
embed = discord.Embed(title="Logs Messages", description=f"Message de {message.author} {message.content}")
await message.channel.send(embed=embed)
channel = client.get_channel(1017579623552405554)```
thx
this was an answer for my question?
Nah nah
there are, but they are pretty bad long-term
either there is some kind of catch, or you're the product
there are some pretty good paid ones here though
https://www.pythondiscord.com/pages/guides/python-guides/vps-services/
On different VPS services
you could invest in a raspberry pi for 40 ish bucks
is it possible to make a function that runs upon finishing watching a linked video? im tryin to do something for my sisters bday in a couple days, and want to create a special interactive experience through my bot. If not, i’m prob going to just have a time delay just over the length of the vid and hope it lines up approximately
perhaps some kind of timer that starts once someone interacts with the vid ?
where is the video and what kind of video
as it’s almost certainly going to exceed discords 8MB max file upload, prob dropbox
I see
Don't know if there's any way to do that through discord, but maybe take a slightly different approach to it, and maybe show something at the end of the video like a command that will send the next message
i don’t recall the formats that standard videos are in either
I think it's still possible to modify video lengths to look infinite, if you want to make them watch the whole thing 😈
yeah i actually was considering that
there's no point in adding a button either 'cause no, I don't think that's possible because you'll never when a client clicked a button/clicked on any link etc.
yup
also how would i set a timer that goes off at a set epoch time?
ie 12pm local time
so not a timeout, but something that’ll go off at x time
id presumably need some kind of bot.event that uses the epoch time as a trigger
I would use a task that checks the time every second or so, then once the expected time is reached, send the message then end the task
the task decorator has a time kwarg that accepts a datetime object
and it'll run whenever the time matches the current time
ah
ooo, never noticed that
same lmao
that’s a decorator on a bot.event ? or where would it go
the task.loop decorator has this kwarg
ah
from discord.ext import tasks
@tasks.loop(time=a_dt_object)
async def my_task() -> None:
...
my_task.start()
bot.run()
there's no involving of events
you might want to stop the task when it runs. The docs say "The exact times to run this loop at", so it might run more than once.
ah ok
so to clarify, id replace the bot after time= with the epoch ?
with a datetime object
or id still need a decorator above
ok so date/time differs from epoch how
i mean how does it convert to local
datetime is apython module, and it's expecting a datetime.time object
I think you could do something like this
from datetime import datetime
from discord.ext import tasks
@tasks.loop(time=datetime.utcfromtimestamp(1662684959))
async def my_task() -> None:
...
my_task.start()
bot.run()
i’ll take a look at that link later!
couldn’t u just import datetime 👀
or is it some kind of weird same-name stacking it has going on
!d datetime.datetime
class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)```
The *year*, *month* and *day* arguments are required. *tzinfo* may be `None`, or an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass. The remaining arguments must be integers in the following ranges...
yup it is
alright
how would i set the loop to check every so and so time ? literally put a check= into it?
check what?
wait stupid me im doubling up; the datetime alrdy does what a check would be doing
my bad
it’s a task on a loop right, will it just loop infinitely until the datetime matches what it’s set to?
most python things check really quick, what stops the task from spamming time checks constantly
No, it'll run it only at the specified times
idk what it does to check the time, but I can look
o
👋
ello snow
hello.
You know what it probably does, it gets the current time and figures out how much time is between the time it starts and the time it should run, then sleeps the task for that long
i’ll have to do some digging later; at the moment im mostly afk tbh
that would make sense 🤔
could be
that's what it looks like at a glance under the hood
fair
well i appreciate the help y’all! i gtg but i’ll lyk how it goes when i get to it
👍
async def on_member_join(member, role):
role = discord.utils.get(member.guild.roles, id="1016124782980366338")
await member.add_roles(member, role)```
Hey, I would like when a member joins my server to add a specific role, can you help me?
try removing member from (member, role) under the add_roles
you get the member when they join and you add_roles to member
Nice thx 
Mine just segfaults when i ask it a question
channel = client.get_channel(1017227196303151255)
await channel.send(f"Bienvenue a {member.mention} sur le serveur !")```
How could I place an embed on this?
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
I know how to make an embed, but I don't know how to place it there @rare echo
channel.send(embed=embedname)?
Ghost ping
some guy asking about youtube and spotify packages
decided to ping you for it
The process of streaming music in a discord bot is mainly impossible or quite hard especially with a platform's TOS and mainly licensing issues
oh i’m aware
Just saying it in general
so im trying to color this text am i missing something here?
this seems to do nothing as well
I don't think you can use multiline code block as a field name
Is there something dumb im missing when trying to color or highlight the background of said text such as help within the embed
trying to do something similar to this
Slash command mentions?
is that how?.. was trying to stay away from the slash commands but if thats the only way
i guess i didnt even think of that
What?
if message.content.lower().startswith('+ticket'):
await message.delete()
await message.guild.create_text_channel(f'Ticket {message.author}')
I would like to set the "permission view"
What exactly does it say
That I would like to put different permission, for example I would like that only the admin + the person who created the channel who see it
What does the warning say
There is no mistake, I am just asking for that.
You just had the correct version in your code
For some reason you edited it and removed the kwarg
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
@vale wing
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
Should I use this?
You mean in how many servers is the user banned in? You can count only ones that the bot is in
That's just the function signature
You need overwrites kwarg
Check example in documentation
Which one?
There's only one isn't there
yes
Then why you asked lol
I'm a beginner in Python, I'm sorry but I don't understand the docs
That's a big issue
I personally don't recommend using d.py if you don't have enough knowledge
You won't last long only with copypasta
Can you explain in a few words?
I just want to modify "view the channel".
I code my bot and after i'm stopping lol.
You need to provide a dict to overwrites kwarg where everyone role and member object are keys and instances of discord.PermissionOverwrite are values
Your decision
can anyone help me with post method
To what endpoint
a website of mine it already works
And uh what kind of help do you need
its just thinking
ive already scripted the script but idk how to get the error
Could you show your code
dms? or here
Here
@commands.has_role(requiredRoleId)
async def ban_user(ctx, userid: str):
await ctx.defer(ephemeral=True)
conn = http.client.HTTPSConnection(websiteUrl)
headers = {"Content-type": "application/json"}
conn.request("POST", BanPath, json.dumps({"userid": userid}), headers)
content = json.loads(conn.getresponse().read().decode("utf-8-sig"))
if json["data"]:
await ctx.respond("\nUsername: %s | > Successfully Unbanned" % (ctx.author.id, content["data"]))
else:
await ctx.respond(content["data"])```
Your code is just blocking
response it
Use aiohttp for requests
!pypi aiohttp
websiteUrl = "" -- website link
BanPath = "" --endpoint
Did you read what I said
oh wait mb
do on.message events cancel out commands? coz yday when i created an on.message bot.event to listen for something containing the bots name and then reply, it caused every one of my bot.command funcs to stop functioning at all
didn’t matter where in the code it was, above or below the commands i was trying to call
it’s like the on_message event overrode them; is that typical? and if so, how would i be able to have both commands and events?
i know i wasn’t using a check=, which may be part of the issue
!d discord.ext.commands.Bot.process_commands
await process_commands(message, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
Changed in version 2.0: `message` parameter is now positional-only.
So I got this command to resolve usernames from userid, how do I make it accept multiple userids instead of just one? Ex; getuser "firstID" "secondID" "thirdID"
async def getuser(ctx, id: int):
user = await bot.fetch_user(id)
print(user)```
@bot.command()
async def getusers(ctx, *, ids):
for userid in ids.split(' '):
if userid.isdigit(): user = await bot.fetch_user(int(user))
Example: !getusers user1 user2 user3
@still iris
Maybe you can skip the isdigit part with type annotation
you can just ```py
@bot.command()
async def getusers(ctx, *ids: int):
...
or use the UserConverter
but that only does a cache lookup
why are you doing this?
isn't msg already a Message object
why are you fetching the message again, just call delete on msg
although that error looks a bit like a bug, what version of discord.py are you on
well that’s an aptly named article lol
Anyone knows a free vps go run discord bot in?
@bot.slash_command(name="unban", description="test")
@commands.has_role(requiredRoleId)
async def ban_user(ctx, userid: str):
await ctx.defer(ephemeral=True)
conn = http.client.HTTPSConnection(websiteUrl)
headers = {"Content-type": "application/json"}
conn.request("POST", BanPath, json.dumps({"userid": userid}), headers)
content = json.loads(conn.getresponse().read().decode("utf-8-sig"))
print(content)
if json["data"]:
await ctx.respond("<@%s>, Successfully banned %s.")
elif json["errors"]:
await ctx.respond(json["errors"])
else:
await ctx.respond("<@%s>, Failed to ban %s. Please try again")```
how to make this request via body
mb this is the c ode
@bot.slash_command(name="unban", description="test")
@commands.has_role(requiredRoleId)
async def ban_user(ctx, userid: str):
await ctx.defer(ephemeral=True)
conn = http.client.HTTPSConnection(websiteUrl)
headers = {"Content-type": "application/json"}
conn.request("POST", BanPath, json.dumps({"userid": userid}), headers)
content = json.loads(conn.getresponse().read().decode("utf-8-sig"))
print(content)
if content["data"]:
await ctx.respond("<@%s>, Successfully banned %s.")
elif content["errors"]:
await ctx.respond(json["errors"])
else:
await ctx.respond("<@%s>, Failed to ban %s. Please try again")
What problem are you having with this command?
the "userid" needs to be in body
not via json dump and idk how to do it
request to my website with body
Why don't you use aiohttp or requests for the HTTP requests?
idk how to do it haha
i'm new to this kind of stuff
I honestly don't know
There are no free VPSes
why are you sending another request just to ban a user
bc it's a roblox game ban
but you can ban people by discord bot
roblox blocked direct connections to discord
@fresh marsh I already told you to use aiohttp, there are examples on their pypi page
And in their docs client quickstart
Yes but you still need a credit card for verification
Which one?
Amazon AWS - free for 1 year
Microsoft Azure - free for 1 year + some services free forever, not sure which ones exactly
Oracle - to my knowledge free forever but they sell your data or smth, you heard the news about lawsuit
idek how to set it up
i mean the aio thing im gonna try tho ty
That message wasn't for you
yeah ik i replied in the wrong message
Ok
You better figure aiohttp out, it's much easier than the thing you are using right now
Hello, SO when i want to download PIP so i can import the modules its showing this Python was not found; run without arguments to install from the Microsoft Store, or disable this shortc, even though, i have PYTHON installed.
Please ask your question here -> #❓|how-to-get-help
This channel is only related to discord bots.
Thank you
It's missing print or await ctx.send line, unable to get output.
Add it then
How would I add a length to the mute? ```py
@client.command()
async def mute(ctx, user: discord.Member, reason):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="Muted")
if not mutedRole:
mutedRole = await guild.create_role(name="Muted")
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False)
await user.add_roles(mutedRole, reason=reason)
await send_mute(user, 'my fancy reason', ctx)```
await asyncio.sleep
why does this ```py
switch = ['off']
@bot.command(name='killswitch')
async def delswitch(ctx, switch):
if ctx.author.id in [..., ...]:
if 'on' in switch:
switch.clear()
switch.append('off')
ctx.channel.send("Killswitch activated.")
elif 'off' in switch:
switch.clear()
switch.count('on')
ctx.channel.send("Killswitch deactivated.")
come up with this error
discord.ext.commands.errors.MissingRequiredArgument: switch is a required argument that is missing.
You need to provide switch argument to your command
when yo urun the comand, did you include the switch?
Store unmute time in a database and periodically check for users to unmute with tasks.loop
e.g. !killswitch on
Or just use timeout
no
How would I do it so the only mute option is one day, so time dnt need to be specified?
Then why did you include it as argument in your function
You would still need to store time in a database
How would I do this
I have an example with temp ban lemme fetch it for you rq
why
Ah thank you, i will create help channel
No need
ah got it working now
Ah okay
ok
cheers
@radiant parrot the loop is here, just noticed that the command is wrong for some reason https://github.com/DevotedExuDevelopersTeam/Core/blob/master/ext/system.py#L78-L91
ext/system.py lines 78 to 91
@tasks.loop(minutes=30)
async def bans_remover(self):
await self.bot.wait_until_ready()
now = datetime.now()
records = await self.bot.db.execute(
"SELECT * FROM bans WHERE unban_at < $1", now, fetch_mode=FetchMode.ALL
)
for r in records:
try:
await self.bot.server.unban(disnake.Object(r["id"]))
except disnake.HTTPException:
await self.bot.log.warning("Failed to unban %s", r["id"])
await self.bot.db.execute("DELETE FROM bans WHERE unban_at < $1", now)```
You just need to understand the principle
What the hell is wrong with this code
Why is log.warning awaited
What was I on
So is that checking the db every 30 mins?
Yeah
How have u created ur db? Like what kinda code
As i have used dbs before but not for discord bot
In most of my projects I use postgres
Including this one
Good thing about it is that it supports time storage
hello, is there a way to remove all role perms from a channel? basically a reset
In sqlite you'd have to store timestamps as integers
!d discord.TextChannel.edit
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 1.4: The `type` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead...
I am not absolutely sure but I think you just need to provide empty dict to overwrites kwarg
!d discord.TextChannel.set_permissions
couldn't find anything regarding resetting perms
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
ah this might work
float ie double
How do i create a postgres db 🙂
Yeah this is the correct thing @rigid narwhal
yep thanks
You need to provide None to overwrite kwarg
Not necessarily, who needs such accuracy
What databases you got experience with
sqlite
me 
can i dm u?
As for sqlite you'd have to store timestamps
unmute_time = datetime.now() + timedelta(days=1)
await execute("INSERT INTO unmutes (id, unmute_timestamp) VALUES (?, ?)", (user.id, unmute_time.timestamp()))```
Some pseudocode for you
why not simply use discord timeout
Excellent question
Thing is there is already a muted role in the server, and I just want to apply this role for one day
Then take the role away
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
this didn't work for me, i have several channels with different role perms, i just want to make all channels public again
then iterate through all that channels and remove all those perms 
yeah how to remove all pems
tried overrides didn't work out
i can go through all roles but thats totally not efficient
almost 200 roles
well if that's that bad as you say you have to remove all roles 

Then just reset the permission to read messages for everyone role in each channel?
How would i use the discord.member.Timeout? Any have example thanks
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
im still bit confused
So, you basically just give it the time that you want the timeout to be put out
from datetime import datetime, timedelta
...
date = datetime.utcnow() + timedelta(minutes=30)
await member.timeout(date)
In this case, the timeout will last 30 minutes
is tht the only bit of code u need for timingout?
Pretty much
Ahh
Or you can just use timedelta
await member.timeout(timedelta(minutes = 30))
Thank you v much
How would fix this error? py await send_mute(message.author, f'Suggesting non-needed post for {channel_sent_in}') TypeError: send_mute() missing 1 required positional argument: 'ctx'
async def send_mute(user, reason: str, ctx):
em = discord.Embed(title="**MUTED**", description=f"{user} was muted because: {reason}",
color=discord.Color.red())
em2 = discord.Embed(title="**MUTED**", description=f"You have been mute because: {reason}",
color=discord.Color.red())
await user.send(embed=em)
await user.send(embed=em2)
@client.command()
@has_permissions(manage_channels=True)
async def mute(ctx, member: discord.Member):
date = datetime.utcnow() + timedelta(minutes=1440)
await member.timeout(date)```
Your send_mute function require 3 arguments
You can just remove ctx from it if you don't need it
async def send_mute(user, reason: str):
em = discord.Embed(title="**MUTED**", description=f"{user} was muted because: {reason}",
color=discord.Color.red())
em2 = discord.Embed(title="**MUTED**", description=f"You have been mute because: {reason}",
color=discord.Color.red())
await user.send(embed=em)
await user.send(embed=em2)
ah yes, sorry became blind for a sec haha
!d datetime.timedelta constructor has many kwargs, not only minutes, take advantage of that
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.
Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
discord.player: ffmpeg process 68 successfully terminated with return code of -11.
constructor isnt the best word to use, initiater is the better word to use
Then it's __init__iater
ok
i want to implement the abilities from pokemon in my pokemon bot so the only way to do it is by making like a million if statements? 😭
you can always replace millions of if statements
wait what
i wrote like 3 and gave up instantly
eh i forgot how to install dpy2..what was the link and all ?
its like there is a battle system and within the system i have added a bunch of IF statements to make the abilties work like for venusaur's overgrow if the health gets below 30% its attacks will get a 50% boost
don't forget -U
to upgrade, if they have existing dpy 1x
pip install -U discord.py
No, even if 2.0.1 wasnt in pypi it technically wouldnt install v1 but v1.7.3
Most annotations are off, some have optional arguments that arent the same type as expected and arent annotated and in a return annotation you used literal syntax for a tuple annotation when you couldve used parametization?
your __all__ dunder should be a tuple, why specify the subclassing of `object and why is their string concatenation when you could just use f-strings
that is true! thanks for the feedback, what do you mean by most annotations?
also the mfa token string concat made more sense than putting that random generation in an fstring
most argument annotations had a flaw off, arg: int = None, this is incorrect as arg's type can be an int or NoneType making it arg: int | None = None
In what sense exactly?
f"mfa.{random.choices(a + 'b' + c + 'd')}"
well, true, ill use typing optional
Just use a list?
Or you can just make a new instance of a string with all those values and then pass it to random.choices
Either way its not really a big deal as its just micro optimization but we have f-strings we should take advantage of their speed and syntax sugar, no?
def __str__(self) -> str:
hmac_chars = string.digits + string.ascii_letters + "-" + "_"
hmac = "".join(random.choices(hmac_chars, k=84))
return f"mfa.{hmac}"
No need to make a variable(hmac) but sure
def __init__(self, id: Optional[int] = None):
self.id = id or Snowflake()
something about putting '' inside f"" is unsettling
No return annotation? Atleast be consistent with its usage
str().join(...) 😳
in init?
why does that need return annotations
Atleast be consistent with its usage
how about this
that is also true
hmac_chars is a constant, so its better to initialize it in the class body instead of the function body
reading my mind
from typing import Optional
from typing import Tuple
you can just use a coma?
from typing import Optional, Tuple
And why the usage of Tuple, i'm pretty sure its been deprecated since 3.9 since tuple has parametization and why inherit from object and atleast use return annotation consistently
well autoformatter splits that import into 2 lines
Thats some weird formatter you got there
that is weird
Either way its useless to import Tuple
yeah, tuple exists
i know, its not supported in 3.8 tho
in most formatters, that is an editable feature, pycharm by default splits in two lines
Why even are you on 3.8
you are doing from __future__ import annotation, so you are fine
I still like Optional
.. | None 💀
?
?
yk what actually this is a silly python script for mocking snowflake and token generation
¯_(ツ)_/¯
not a code written in rust to make rockets aim at tanks lmaoo
ty for the idea :p
hes using __future__.annotations
It converts every annotation into a string so, yes.
Looks nice
those two constants, i would personally define them in the class body. It indicates the usage more clearly ig
i would need to defined them twice tho
and theyre not in __all__ so
oh, you are using it else where
its used in Token and MfaToken
Then yeah youre good
👍 didnt notice
can someone help me with my bot to make the command work only if it has member role for example tag me or dm pls
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
@bot.command(name="unmute")
@commands.has_role("Admin")
async def unmute(ctx, user: discord.Member):
role = discord.utils.find(lambda r: r.name == 'Member', ctx.message.server.roles)
if role in user.roles:
await bot.say("{} is not muted".format(user))
else:
await bot.add_roles(user, role)
should i add it at the top before @command.has ?
this is not my code
This is so sus code
str.format🙈
that don t work
Very precise i must say
yeah
bruh it wont work like that you need to pass it the role name "as a string" or the role id as an int 12312312
it converts every annotation to a string
that is not an annotation
Youre using it as a union
!e
from __future__ import annotations
def foo(x: int | None):
...
print(foo.__annotations__)
@iron sorrel :white_check_mark: Your 3.11 eval job has completed with return code 0.
{'x': 'int | None'}
its a string here as you can see ^
!e
from __future__ import annotations
def foo(x: int | None):
...
assert isinstance(foo.__annotations__["x"], str)
@iron sorrel :warning: Your 3.11 eval job has completed with return code 0.
[No output]
it work with that thank you !
yes, to support legacy py versions
Version safety? what
yw
new in 3.10
what?
u can do that in 3.9
but not in 3.8 iirc
basically making code compatible over multiple versions
I still dont understand
what? doesn't match case mean this?
match var:
case 5678:
...
case 56789:
...```
You mean match case trees?
trees 🗿
i remember stella's bot in discord.py having commands to generate and parse tokens, unfortunately i havent seen her bot online anymore
like, i have this 3.10 type annotation int | None, If I give to someone who is on 3.8, it will not work. But when i make the future import, it does. It is not the best Solution and if you trying to make your code compatible for older versions, you should certainly not do that, but this is one way.
Thats what i'm saying
I already know that, but how does that relate to match and case kek
stella?
how about 3.8?
nope
What parametization?
the thing is, python is not rust, future features are not compatible with past versions
gud logical "python is not rust"
all the code written now, will be compatible with rust in the future but anyways so offtopic
rust good 🚀
no
no
i like C++ better
oh yeah cpp is gud
afaik she was part of the discord.py server for a long time, a lot of people knew her
I personally like C++'s syntax better and its concepts over Rusts
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
ok
why does it always send ot2 channel 🗿
because of channel activity
But its one of the most inactive ones right now🐧
thats the point...
that is why 🗿
yes :hahaa:
It redirects you to a channel to take the continue the conversation without disrupting an already existing conversation.
Im just joking around lol
weren't you saying to not fool around some time ago
Didn't you said not to fool around some time ago?*
.topic
Suggest more topics here!
didn't you said 🗿
ok
ok
lol
interesting 
A free pass to rant about discord
idk maybe they should actually use API versions for breaking changes
I got you, Discords mobile client is shit and inconsistent in every spec, Its API is even worse especially with new upcoming features
Back in the good old days where Discord bots were a simple way to have fun and not a absolute nightmare of entitled users and forced rewrites
at least they sorta fixed that with react on android
but now android discord is trash
Sorta? The whole client is buggy and feels "unsnappy"
It feels like i'm using WhatsApp in 2014
💀 no that is too much
😔 i think part of the problem is newer APIs don't have as many stack overflow questions so more people go to discord channels and ask really basic python questions
100% agree but at least feature parity is better
ex Locales didn't work on android until react native iirc
My issue with it is generally Discord are very vague about intents requirements and don't actually enforce anything. Which doesn't help users where some bots will just use text commands and others will use slash
yeah
And people still can't work out how to use slash commands!
that is such a mess bruh
im not sure what its like outside of the hikari world, but at least for hikari theres not many questions about it.
terrible choice of words silly master32
I mean the people actually using the bot, not the people writing the bot.
Feature wise its alright, but some features are quite annoying or not even working at all

it's the reason why I tell people they don't want to make a big bot, at the start it's fun but then it just becomes a second job dealing with people not being able to read simple things at times. All the time.
There's somewhat less user evolvement with lib dev
although I think Discord related library development is probably one of the easier things to do and get burnt out on
yeah, i did get burned out from working on lib for about two months. Did come back to it though.
anyone help me??
How to send to user dm only slash cmd
@client.tree.command(name='hello', description='You test bot lmao')
async def hello(interaction: discord.Interaction):
await interaction.response.send_message("Hello World")
Ephemeral?
So user can only use the command inside dm?
interaction.user.send
@commands.slash_command(name="hack", description="Hate someone? Hack their account!")
async def HackUser(self, inter, target: disnake.Member):
Message = await inter.send(f"Hacking {target}...")
await asyncio.sleep(3)
await inter.edit(f"1")
await asyncio.sleep(2)
await Message.edit(f"2")
await asyncio.sleep(2)
When I did it with prefix cmds, it worked but with Slash_commands, it sends me the error:
"HackUser
await inter.edit(f"1")
AttributeError: 'ApplicationCommandInteraction' object has no attribute 'edit'"
How do I fix this?
inter.send -> inter.channel.send
Ahhh, Nice. Thanks!
I made this rps bot
class rpsmenu(discord.ui.view):
def __init__(self) -> None:
super().__init__()
embed=discord.Embed(title="RPS" ,description="Choose Your Move", colour=0x552E12)
@discord.ui.button(label="Rock", style=discord.ButtonStyle.grey, emoji=":dsrock:")
async def rock(button: discord.ui.Button, interaction:discord.Interaction):
embedrps=discord.Embed(f"{randomrps}\n**Your move:** {interaction}")
await interaction.response.send.send_message(embed=embedrps)
@discord.ui.button(label="Paper", style=discord.ButtonStyle.grey, emoji=":paper:")
async def paper(button: discord.ui.Button, interaction:discord.Interaction):
embedrps=discord.Embed(f"{randomrps}\n**Your move:** {interaction}")
await interaction.response.send.send_message(embed=embedrps)
@discord.ui.button(label="Sissors", style=discord.ButtonStyle.grey, emoji=":sissors:")
async def sissors(button: discord.ui.Button, interaction:discord.Interaction):
embedrps=discord.Embed(f"{randomrps}\n**Your move:** {interaction}")
await interaction.response.send.send_message(embed=embedrps)
@bot.command()
async def rps(ctx):
view = rpsmenu()
embed=discord.Embed(title="RPS" ,description="Choose Your Move", colour=0x552E12)
await ctx.reply(embed=embed, view=view)
and now I am getting this error
File "c:\Users\8ster\OneDrive\Desktop\projects\Discord Bots\Mighty Raju Bot\main.py", line 68, in <module>
class rpsmenu(discord.ui.view):
TypeError: module() takes at most 2 arguments (3 given)```
discord.ui.view is a module, the actual class you want to inherit from is discord.ui.View (capital)
also in the latest version of dpy 2.0, the functions should have a signature of (self, interaction, button), not just (button, interaction)
A file is the more appropriate word, as modules are stdlibs
also try to have a fixed timeout if the view is not persistent 
python scripts are modules
yes?
are u a dictionary? 😳
noid just loves providing opinions 

@pulsar solstice see the points above and also:
interaction.response.send_message(...)is what you meant to write- standard emojis like
":scissors:"arent recognized by discord and have to be written in their unicode equivalent, i.e. "\✂️" or"\u2702\ufe0f"(unicode escapes)
they are costom emoji in my server
discord would require the format of <:NAME:ID> then, e.g.
becomes !python
you can type your emoji with a prefixed backslash to see that custom emoji format
it actually works in my server but if u are sayin then I should apply it
I was too lazy to do that irl
hmm i havent been able to make it work
add_reaction() and Button emoji= with ":xyz:" just gives me error code 400
missing 1 required keyword-only argument: 'intents'
what is this?
dpy 2.0 requires you to specify the intents your Client or Bot will use
do i paste this?
Simple Bot creation
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix=["!", "?"], intents=intents)
Advanced Bot creation
class MyCoolBot(commands.Bot):
def init(self):
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
super().__init__(
command_prefix=["!", "?"],
description="My Cool Bot!!!",
intents=intents,
)
you read this
oh
hey your example actually enables message_content this time
(i mean in comparison to !intents which uses commands.Bot but without message content)
🚶♂️
I am getting this error
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 423, in _scheduled_task
await item.callback(interaction)
File "c:\Users\8ster\OneDrive\Desktop\projects\Discord Bots\Mighty Raju Bot\main.py", line 74, in rock
embedr=discord.Embed(f"**My move:** {randomrps}\n**Your move:** :dsrock:")
TypeError: Embed.__init__() takes 1 positional argument but 2 were given```
what does it mean?
no args for embed, only kwargs
how to add it in there?
Embed("...") - wrong
Embed(title="...") - right
or i think in your case it's description="..."
i still dont understand xd
what exactly do you not understand?
sad... what did you understand from what I sent then?
nothing fr
im new to coding
!resources @mild nimbus here you can find resources where to learn python
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
ty
getting anoyher enexpected error
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 423, in _scheduled_task
await item.callback(interaction)
File "c:\Users\8ster\OneDrive\Desktop\projects\Discord Bots\Mighty Raju Bot\main.py", line 83, in sissors
await interaction.response.send_message(embed=embeds)
AttributeError: 'Button' object has no attribute 'response'```
CODE:
class rpsmenu(discord.ui.View):
def __init__(self) -> None:
super().__init__()
embed=discord.Embed(title="RPS" ,description="Choose Your Move", colour=0x552E12)
@discord.ui.button(label="Rock", style=discord.ButtonStyle.grey, emoji=":dsrock:")
async def rock(self, button: discord.ui.Button, interaction:discord.Interaction):
embedr=discord.Embed(description= f"**My move:** {randomrps}\n**Your move:** :dsrock:")
await interaction.response.send_message(embed=embedr)
@discord.ui.button(label="Paper", style=discord.ButtonStyle.grey, emoji=":paper:")
async def paper(self, button: discord.ui.Button, interaction:discord.Interaction):
embedp=discord.Embed(description=f"**My move:** {randomrps}\n**Your move:** :paper:")
await interaction.response.send_message(embed=embedp)
@discord.ui.button(label="Sissors", style=discord.ButtonStyle.grey, emoji=":sissors:")
async def sissors(self, button: discord.ui.Button, interaction:discord.Interaction):
embeds=discord.Embed(description=f"**My move:** {randomrps}\n**Your move:** :sissors:")
await interaction.response.send_message(embed=embeds)
@bot.command()
async def rps(ctx):
view = rpsmenu()
embed=discord.Embed(title="RPS" ,description="Choose Your Move", colour=0x552E12)
await ctx.reply(embed=embed, view=view)
dpy swapped interaction and button places iirc. smh
in your function you do self, button: ..., interaction: ...
and it is self, interaction: ..., button: ...
or wait i guess nothing changed
bruh i have no idea 🗿
anyways its like this
i think yes?
why is it
showing this
My move: My move: RockMy move: PaperMy move: Sissors
Your move: :dsrock:
how do i know why?
like I used random.choice
and it is choosing so many outputs
well actually I do know, you did something wrong in code
should I send the full code?
maybe?
Hey @pulsar solstice!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
!e
import random
d = {0: "🪨", 1: "🧻", 2: "✂️"}
def foo(x: int, y:int) -> None:
z = (x + 1) % 3
print(f"player move {d[x]}")
print(f"opponent move {d[y]}")
if z == y:
print("p2 won")
elif x == y:
print("draw")
else:
print("p1 won")
mine = random.randint(1,3)
opp = random.randint(1,3)
foo(mine, opp)
@shrewd apex :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | player move 🧻
002 | opponent move ✂️
003 | p2 won
yay
Giving your own opinion can enlighten the user(s) and the author and can give many other mind sets or opinions and knowledge that may benefit both the author and user(s)
You can always use a dict or match case trees
i never said it was wrong i don't mind anyone sharing their opinions 😉
Just saying it in general so people can understand, i dont pick arguments with users because i want a discussion with them about their vision/opinion
match case works with == in their cases?
👍
It wont exactly work well, so nevermind that
enable message_content intent, if you are on dpy 2.0
i think for using == i would have to do something like True if x == y iirc
nothing
now work ty
how to send a message without a message or ctx attribute?
I want my bot to send a message in a class()
!d discord.abc.Messageable
class discord.abc.Messageable```
An ABC that details the common operations on a model that can send messages.
The following classes implement this ABC...
You can send with objects of any classes that implement this
class menu(discord.ui.View, discord.abc.Messageable):
def __init__(self) -> None:
super().__init__()
like this?
No what
lol
It's kinda funny tho lol
you probably want to send a message on some interaction, right?
yup
!d discord.InteractionResponse
class discord.InteractionResponse```
Represents a Discord interaction response.
This type can be accessed through [`Interaction.response`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.response "discord.Interaction.response").
New in version 2.0.
in the callback, the decorator passes in a discord.Interaction object, you can use that to send messages ^
Check the methods of this, for eg send_message
Some reason this is not muting the user? ```py
async def send_mute(user, reason: str):
channel = client.get_channel(925912014398844998) # channel mute case put in
em = discord.Embed(title="MUTED",
color=discord.Color.red())
em.add_field(name='Member:', value=f'{user}')
em.add_field(name='Duration:', value='1 day')
em.add_field(name='Reason:', value=f'{reason}')
em.set_footer(text=f'Provided by Donks#1048 • {current_time}')
em2 = discord.Embed(title="MUTED", description=f"You have been muted because: {reason}",
color=discord.Color.red())
await channel.send(embed=em)
await user.send(embed=em2)
@client.command()
@has_permissions(manage_channels=True)
async def mute(user: discord.Member):
date = datetime.utcnow() + timedelta(minutes=1440)
await user.timeout(date)```
await interaction.response.send_message(f'Disapproved and muted user!')
await send_mute(message.author, f'Suggesting non-needed post for #{channel_sent_in}')```
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
Is it timezone aware dt
dont u need a ctx arg 
anyway i can get ctx from interaction
What are you going to do with the ctx
ah no, how to do tht?
tryna make a an interaction check but im using slash commands so like idk what to do:
class Butto(nextcord.ui.View):
def __init__(self, ctx):
super().__init__()
self.ctx = ctx
async def interaction_check(self, interaction):
return self.ctx.author == interaction.user
@nextcord.ui.button(
label = "Send",
custom_id="send",
style=nextcord.ButtonStyle.green,
row=1
)
async def send(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
embed = nextcord.Embed(
description="eeeee"
)
await interaction.response.send_message(embed=embed)
class Tester(commands.Cog):
def __init__(self, bot):
self.bot = bot
@nextcord.slash_command(description="📜 test shit")
async def create(self, interaction: nextcord.Interaction):
view = Butto(ctx = interaction.)
embed = nextcord.Embed(
description="jhdhjehked"
)
await interaction.response.send_message(embed=embed, view=view)
Its not necessary. You can pass the timedelta directly
And add ctx param like master said
So why are you calling it ctx lol
Just pass the original interaction to the view and check if the users are the same
huh
where wld i pass this? 🙂
guys how do i use ephemeral messages ?
I think i have?
i was looking at how other ppl had "got ctx from interaction" and they did some other thing
the messages only a person can see when clicking a button for example .
Ur adding it to a datetime which is unnecessary
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
Wrong doc
?
so just have timedelta(minutes=1440) ?
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
Yes pass that directly
wow i am a lot with the 3 dots at the end
And add ctx param
here ephemeral arg
@client.command()
@has_permissions(manage_channels=True)
async def mute(user: discord.Member):
date = timedelta(minutes=1440)
await user.timeout(date)``` better?
hi does anyone know how i can remove all those its not error its just if user don t have role member it do that
all red
And this @radiant parrot
ctx arg? 
Error handler
@client.command()
@has_permissions(manage_channels=True)
async def mute(user: discord.Member, ctx):
date = timedelta(minutes=1440)
await user.timeout(date)```?
🗿
am i forgetting something
yes you are
i get an error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'Context' object is not callable
ah
what is your code 😳
my code
@bot.command() async def test(ctx): await ctx(content="hi", ephemeral=False)
wot am i missing haha
await ctx() waht do you want that to do bruh
no?
yes
but i mean how i stop those cause idk how ?
i will see thx
interaction failed
ctx is first param of command
ceode 🗿
And actual error
i cant say what is wrong with just "interaction failed"
Hey @feral frost!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
:é
ig usually when it says "interaction failed" it does not give an error
at least that is how it was for me
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
Im so confused sru
`await interaction.response.send_message(content="test", ephemeral=True)
ticket.callback = button_callback
view = View()
view.add_item(ticket)
await ctx.send(view=view)`
how to check whether the person who sent the command and the person who interacted with a button in that message the same person or not?
The first parameter of a command callback is ctx(Context)
its for a ticket system @silk fulcrum
in this? py async def button_callback_2(interaction): await interaction.response.send_message(f'Disapproved and muted user!') await send_mute(message.author, f'Suggesting non-needed post for #{channel_sent_in}')
In the command bruh
ohh sry didnt read right
my whole code
@client.command()
@has_permissions(manage_channels=True)
async def mute(user: discord.Member, ctx):
date = timedelta(minutes=1440)
await user.timeout(date)```
I think that is because it takes longer than 3 seconds to respond to the interaction when the user clicks the button, await interaction.response.defer() to avoid that
Yes, now first parameter is ctx, and second parameter is user
@client.command()
@has_permissions(manage_channels=True)
async def mute(ctx, user: discord.Member):
date = timedelta(minutes=1440)
await user.timeout(date)
Yes
discord.errors.InteractionResponded: This interaction has already been responded to before
i get this error now
so this will now timeout the user?
Possibly
do i have to put something in the ()
this is the error
epher thingy is on True right ?
IT WORKS
THANKU
yeah only me
i can explain how to set the intents
no you helped me
Might want to reset your token
he didn't reveal the whole thing tho 
that is a token anyways tho 
Yeah that’s like telling everyone 9 out of 10 characters in your password
lmao
who so jobless to brute force the rest
Great that leaves us about 35 possibilities, should be able to brute force you in.. let’s see.. 20 milliseconds
less
💀
creepy
🙂
it looks like one of those medical dummies in hospital
lol
lmao
The ones you have to do mouth to mouth resuscitation on
Very awkward
2022-09-09 19:10:20 INFO discord.client logging in using static token
2022-09-09 19:10:21 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 6122749679dfcb88596b412fdb8b5d9b).
Bot is connected to all of the available servers in the bots mainframe.
2022-09-09 19:10:44 ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "unban" is not found
i run my main.py and it works fine as you can see before "Bot is connected" but then when i try to do the command which is ",unban" following with the member's discord id, then it brings an error (the command is in my cogs file)
heres the start and end of cogs
Doesnt really matter, He even showed the most important part
@ me when you reply so i can reply back please!
Traceback (most recent call last):
File "", line 13, in <module>
client = commands.Bot(command_prefix="!")
TypeError: init() missing 1 required keyword-only argument: 'intents'
Youre using the incorrect method
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.10)").
You shouldnt load cogs inside of on_ready either as its prone to errors
is this a raid of dpy 2.0 upgraders?
it's a 3rd one iirc
it's ppl who ran pip install -U discord.py
can you guide me by telling me what exactly i have to do to fix my problem, use the correct method?
?
yours should be changed to look similar to this
You use the method provided: #discord-bots message
i dont understand the docs, as many times as i look at it, i cant seem to understand it
Traceback (most recent call last):
File "", line 94, in <module>
client.run(token, bot=True)
TypeError: run() got an unexpected keyword argument 'bot'
Well, do you understand the OOP paradigm?
but i have read all but i mean how i can do to not have all those error pop up can t the error be silente ?
Its not a kwarg anymore
huh
hi does anyone know how i can remove all those its not error its just if user don t have role member it do that
nope, i looked at videos on classes and the OOP but still dont understand
!d discord.discord.ext.commands.on_command_error
discord.ext.commands.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.
A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
You need to take a more hands on approach with classes
Conceptually they can be difficult to learn so watching someone else talk about it in a video won’t help much
Well maybe read up on it again, can you provide which tutorial you followed?
so, what should i do
where in my code do i put that
You need to actively try to implement it wherever you can
sure, 1 sec
You remove it?
what?
Its mostly a life skill, whatever you learn or study should always be tried as it can raise further questions that will make you more knowledgeable on the topic
https://www.youtube.com/watch?v=ZDa-Z5JzLYM&list=PL-osiE80TeTsqhIuOqKhwlXsIBIdSeYtc&index=1 this playlist
In this Python Object-Oriented Tutorial, we will begin our series by learning how to create and use classes within Python. Classes allow us to logically group our data and functions in a way that is easy to reuse and also easy to build upon if need be. Let's get started.
Python OOP 1 - Classes and Instances - https://youtu.be/ZDa-Z5JzLYM
Python...
it has 6 parts
Yep thats a good tutorial, i recommend you do OOP exercises and watch the full tutorial but dont watch one and then the other episode take your time until you fully understand that concept and then you can jump to the next
ERROR: Could not find a version that satisfies the requirement bot (from versions: none)
ERROR: No matching distribution found for bot
WARNING: You are using pip version 21.2.4; however, version 22.2.2 is available.
You should consider upgrading via the 'C:\AppData\Local\Programs\Python\Python39\python.exe -m pip install --upgrade pip' command.
when i try to load "bot" package
alright thank you ill try to do that, for now since i want to fix my current issue, could you help me with it real quick, so i can actually fix this before moving onto learning more about OOP
client.run(token)
Can you show your current code
main.py or cog
