#discord-bots
1 messages · Page 105 of 1
wait bro let me show you
😡
i am facing this issue
@bot.command(aliases=["Amongus"])
@commands.cooldown(1,500,commands.BucketType.user)
async def amongus(ctx):
member = ctx.author
channel = bot.get_channel(1005776398507581490)
check = bot.get_channel(1005774386923569213)
checking = bot.get_channel(1005774410415886378)
hii = bot.get_channel(1005774465055084564)
blah = bot.get_channel(1005774489591754822)
ga = bot.get_channel(1009527767240552489)
ta = bot.get_channel(1006594487587450972)
me = bot.get_channel(1010995214325923950)
if member not in channel.members:
ctx.reply(" [#1005776398507581490](/guild/267624335836053506/channel/1005776398507581490/)אתה לא יכול להריץ את הפקודה כאן! אנא נסה להריץ אותה בחדר ")
if check is None:
ctx.reply("בבקשה תכנס ללובי!")
if checking is None:
ctx.reply("בבקשה תכנס ללובי!")
if hii is None:
ctx.reply("בבקשה תכנס ללובי!")
if blah is None:
ctx.reply("בבקשה תכנס ללובי!")
if ga is None:
ctx.reply("בבקשה תכנס ללובי!")
if ta is None:
ctx.reply("בבקשה תכנס ללובי!")
if me is None:
ctx.reply("בבקשה תכנס ללובי!")
else:
voice = ctx.author.voice.channel.mention
emibed = discord.Embed(title="מחפש שחקן למשחק אמונג אס", description=f'{ctx.author.mention} Among us מחפש מישהו לשחק! ',color=0x6c97c5)
emibed.add_field(name="המשתמש נמצא בוויס:", value=voice, inline = False)
await ctx.send(f" {ctx.author.mention} מזמין אתכם לשחק איתו! <@&890044017776136202>", embed=emibed)```
```[2022-10-12 18:12:04] [ERROR ] discord.client: Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Among Us IL Bot\main.py", line 199, in amongus
voice = ctx.author.voice.channel.mention
AttributeError: 'NoneType' object has no attribute 'channel'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Among Us IL Bot\main.py", line 168, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'channel'```
You keep sending this like 4 times
help him
i changed things
I love how I'm telling everyone to help others when I'm not doing anything kek
Like we've shown, you need to pass in the intents kwarg, like was shown in that embed, and the other code screenshots you've been sending
lol
!d discord.Member.voice
property voice```
Returns the member’s current voice state.
The voice can return None iirc
what i need to do then?
wdym
my bot didnt come even online
if member not in channel.members:
what to change it to
pass in the intents kwarg
can you tell code please
You did it here
i am a fresher
???
i dont understand
i didnt get
Read the error
Your ctx.author.voice returned None
i know
but thats why it supposed to send if check is None:
ctx.reply("בבקשה תכנס ללובי!")
You should have a check to check if the user is in a guild
me?
!d discord.ext.commands.guild_only
@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.
This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
If used on hybrid commands, this will be equivalent to the [`discord.app_commands.guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only") decorator. In an unsupported context, such as a subcommand, this will still fallback to applying the check.
Yes!
@bot.command(aliases=["Amongus"])
@discord.ext.commands.guild_only()
@commands.cooldown(1,500,commands.BucketType.user)
async def amongus(ctx):
to try now?
AM2i9 you here?
It's requiring you to pass in an Intents object into the intents kwarg
intents = discord.Intents.default()
# Enable the intents you need
intents.members = True
discord.Client(intents=intents)
```If you're new to python, and not just to discord.py, I would stop this and take the time to learn python in general. discord.py is rather advanced
which platform should i prefer to learn from basics
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
There are some good ones here
ohk thanks buddy
I want to make a command for my bot that would act as the search bar for my websites
How would i do that?
Hi guys, any clue how to use slash commands with python?
use discord.py interactions
it's a library? does it have any down side?
yea that
its baked into discord.py now, but there are other forks that people use as well. but if youve already got something built with discord.py you might as well stick with it to avoid conflict
i ran into that problem about a week or so ago
Is someone here familiar with MYSQL interactions?
well, more specifically if i have mydb.close() somewhere in my code is that going to cause disconnect problems? do i have to close the connection at all or can i just use .commit()?
u can just commit after writing in db
alright. wasnt sure if that would cause multiple connections or not
are u using a single connection across whole code or making connections throughout
single connection for the whole code then using cursor to execute throughout the code
coz if u close when u are using a single connection then the connection is closed across the whole bot
!discord.timeout
just use asyncpg
ah alright. thanks
and enable autocommit
!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 [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
ive already got more than half my project written with commit at the end of my work, not going to mess with it lol
@sick birch do I need to install a module for it?
Only discord.py
Tell the problem
Come at #help-honey @naive briar
If someone can help me to fix my level system come to #help-honey
and if you put timeout on the mute command, will it be possible to set your own time for which you want to give mute ?
async def invite(self, ctx):
em = discord.Embed(color=000000)
em.add_field(name="Invite Divine")
em.set_footer(text="[]()")
await ctx.send(embed=em)```
anyone know why this doesnt work?
you didn't close the bracket of the Embed object
can someone help with this
show your full cog not just a part of it
from http import client
import random
from secrets import choice
import discord
from discord.ext import commands
import os
import asyncio
class Utility (commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.command()
async def invite(self, ctx):
em = discord.Embed(color=000000)
em.add_field(name="Invite Divine")
em.set_footer(text="[]()")
await ctx.send(embed=em)
async def setup(client):
await client.add_cog(Utility (client))```
bad indentation
Can I get money by making bots ?
yes
?
How
Oh so by selling bot scripts ?
...
stop ?ing and speak what part of "bad indentation" you don't understand
that too ig making bots for others
bro i dont understand the error
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Like I gotta invite the bot in thier server or what lol
your invite function should be inside the Cog class.
How to give people bots
Lol sorry
- You make a bot lets say an example economy bot where u have coins now u can make coins pay to get this is economizing ur bot
- Others want to make bots but sometimes lack time or skill so u make bots for them and they pay u
there maybe other avenues for earning but idk
4 message 4 ping
or stop thinking of earning thru bots
don't want to sound mean but thats probably the worst way of getting paid. every next person i see is a bot developer 🗿who is ready to work for money.
Nah I was just wondering I am not even gonna try to get money by that lol
I just make bots for fun and cuz I like it
well as sage said people add paid only features in their bots to get money, other sources can be patreon kind of stuff
indirectly it revolves around "pay to get <x> thing"
Oh yeah I understand
async def invite(self, ctx):
embed = discord.Embed(title="Invite Divine", description=f"[]()", color=discord.Colour.black())
embed.set_footer(text="{name} Made this Embed")
await ctx.send(embed=embed)```
why does it say
there's no black color attribute
you can just use the hex
it was 0 iirc
when i do that its an error
im trying to do 18191c
it would be 0x18191c
i want the embed to be the same color as discord dark mode
always add 0x before hexs and don't call it
so 0x18191c
doesnt work
show updated code
async def invite(self, ctx):
embed = discord.Embed(title="Invite Divine", description=f"[]())
embed.set_footer(text="{name} Made this Embed")
await ctx.send(embed=embed)```
oops
i don't see anything related to color.here
async def invite(self, ctx):
embed = discord.Embed(title="Invite Divine", description=f"", color=0x18191c())
embed.set_footer(text="{name} Made this Embed")
await ctx.send(embed=embed)```
don't call it
remove the ()s after it
u told me to
i asked to not call it? if you don't know what calling an object in python means you seriously need to learn more
rewrite the code again it will work
this error happens when you mix tabs and spaces, just rewrite with any one of these will fix it itself
dawg why cant u just tell me
@slate swan and in order to make a timeout in mute, you need to write a time variable and a reason variable into it ?
add 0x and remove () ... how can i put it more simply?
do you mean a discord timeout when you say mute?
yes
you do need to provide a datetime or timedelta in the timeout method, but reason is optional
that is, you need to write await timeout(timeout + reason)
no
await member.timeout(datetime/tinedelta object here, reason="reason")
!python
what is the name of the second line?? footer? description?
i did the invite part
i just dont know the 2nd line
This thing?
no like whats the embed name of the 2nd line
If you're using dpy it's value attribute under add_field
not this
thanks ill try it rn
i dont want an title
embed = discord.Embed(description="test").add_field(name="Invite", value="what ever you want here")
This is an example
async def invite(self, ctx):
embed = discord.Embed(title="Invite Divine", description=f"Invite the Bot click [``Here``]()", color = 0x18191c)
embed.add_field(value=f"")
embed.set_footer(text=f"Invite the Bot!")
await ctx.send(embed=embed)```
unfortunately they're required. You can use an invisible character like \u200b if you really don't want a field name
one sec I get what you mean
theres not another embed name that doesnt require an title??
okay
how so?
im trying to do this i have the invite part the title and the footer just not the 2nd line
embed= discord.Embed(title="Invite", description="whatever you want here")
I suppose that's what you want
i already have that tho
Then
"Invite" is an embed title
next 2 lines are the description
last line is a footer
i can just do embed = discord.embed(description="") on the next line?
If you want to make a new line just do \n inside the string?
No you can only have 1 description iirc
^
im confused
I suppose you're trying to use multiline string?
i just wanna do this man 😭
Here at the end of your description inside the string add \n and just continue.
And just add whatever you want and it'll pop up in another line
embed = discord.Embed(title="Invite Divine", description=f"Invite the Bot click [``Here``]()\n", color = 0x18191c)
Yes, and now add whatever you want after \n
so i can just do , description=f"whatever", color = 0x18191c)
after the \n
The purpose of \n is to make a new line for a string in the compiler (here it's your bot) without you having to actually do it in your code
And I'm kind of confused what does this have to do with what you're trying to do
I think I get what you mean
thats what i want to put after the \n
embed = discord.Embed(description="This is line 1\nNow this is line 2, hope this explains it")
You just slap a \n inside the string without adding another description and it'll create a new line for you
Just paste this example and test it to see what I mean
it worked tysm
My pleasure
would you happen to know the hex code of discord dark mode so like it blends in
No sorry
Maybe you could take a ss of your screen and paste it in a painting app an use the colour picker tool, and with that you could find the hex? Maybe?
Idk it would be too much work lmao
!d discord.Colour.dark_theme
classmethod dark_theme()```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") with a value of `0x36393F`. This will appear transparent on Discord’s dark theme.
New in version 1.5.
it's built in for you
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.
show the full traceback
thats the full thing
thats the full thing dude
I doubt it, python errors don't start with an indent
They're also usually not that short unless you have a really bad error handler set up
Increase the size of your terminal or scroll
Scroll please?
cant scroll
wheres the up arrow at
ok i got it
imma send error in pastebin
Why are you importing from typing import AsyncIterable, AwaitableGenerator if you don't use either of these?
i didnt mean to
i got rid of and now this is the only error
em = discord.Embed(colour="0x36393F"(), description=f":approve: {context.author.mention}: Set the slowmode delay to **{seconds} seconds** in {context.channel.mention}")```
why are you calling the string
this is the darkmode embed color, yes?
just use discord.Colour.dark_theme()
mhm
yo is there a parameter parser i can use when handling message content?
ping me with response or need more context - thanks!
Just a suggestion, it's a good practice to use is keyword when you're checking if a variable is of None type and the same goes to booleans. So instead of member == None, do member is None
Although both works it's a really good practice to use is in right cases
or do not member since statements default to true so you are checking its false
But here the member object will only be of None or discord.Member type I cannot be a boolean
Here he as predefined member to be None if user is not mentioned not true or false
well there is a shorter way for you, either works just what you prefer yk
right
in reference to slash commands, is there a way to say - if no optional arguments are provided, do this
I believe the default value is None if you set it to optional, so you can check if arg is None: ... and do something
how can i play sound in voice chat ? i can let my bot join but cant play a simple part of sound
but would i have to list all 10 arguments in this? trying to send a message if they use none
pls help
I'm not understanding, sorry
would i have to do something like if arg1, arg2, arg3, arg4, arg5, etc is None:
if all(arg1, arg2....) will be False if any of them is None
Oh, you want to check if all of them are none or just one of them?
i want to check if all arguments are none
Then yeah do as sarth said
Where is the problem
Though if you're just going to send a message telling the user to include the arguments, you may as well just make the required and handle the errors seperately
I see too often people making arguments optional only to tell the user it's not optional
A bit counterintuitive if you ask me
is there a way to make any 1 of the arguments required? id like for them to be able to set one variable or all if theyd like so theres 10 optional ones
just use a slash command at this point
so i have an if statement for each not being None, and i was just going to send a message saying they need to include 1 argument if they dont
i am
yeah then you can set all arguments as optional
i did
and then check if all args are None, if they are then raise your error
you can use if not any(arg1, arg2...): for that
!e ```py
a=None;b= None
if not any({a,b}): print("use atleast 1 arg")
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
use atleast 1 arg
yea i was trying to avoid listing all the arguments to make it look nicer if possible but ill probably do that. thanks
i added this into my code and it tells me the application did not respond if any of the args are there. i even put the arguments behind an else: statement and it still sends it if i give an argument
okay first thing
you don't need to make.the list uou can just do ```py
if interaction.data["options"] == []:
#no Option was used
!d discord.Interaction.data
The raw interaction data.
yeah should work
well if an argument is provided then it responds to the interaction with a message saying the variable was updated
could you show ur code
well, i guess its not technically a response, if a variable is updated it sends a message in the channel for each variable provided. providing code in this case is easier said than done. im on a remote vm that doesnt let me copy paste outside the window
its not a response then. you actually need to use interaction.response to create a response
hmm alright
got it working like a charm now. thanks again
alright onto the next problem im having. i have an on_message event and during that i grab the message.guild.id. however, when an ephemeral message is sent i cant grab that object. how can i handle that attribute error if message.guild comes back as NoneType
guild=message.guild.id
if message.author.bot == True:
return
else:```
do something```
Question, I'm using walk_commands and recieve a groups subcommands as expected.
ex: ?role humans
I recieve humans and any other subcommands within that group.
But humans, is also another group with the subcommand remove
ex: ?role humans remove
Is there a method that can retrieve both role , humans and the commands within humans?
I want to retrieve it as role humans remove
It's saying message.guild doesn't exist for an ephemeral message therefore .id can't be none
Because it doesn't exist
yeah then check if message.guild is None
if it has no guild you can do hasattr(message, "guild")
i assume it would still have the attribute though, i've never tested with ephemeral stuff
for some reason it doesnt, idk. check for message.guild works, thanks
is it possible to use these brackets {} in a f-string without making it work
{{hello}}
like i want to use {usermention} without making it a f string but I NEED an f-string
No documentation found for the requested symbol.
No documentation found for the requested symbol.
why can’t you use an f string o.O
Is there a way I could make like a grid of buttons for a minesweeper type of gamemode?
like this
sure, just know that discord only allows 5 buttons per row and 5 rows per message
When they are not in a voice it shows error
Wasn't it 3?
ive tried minesweeper with select menus to manage larger grids, but its a bit clunky having to click up to 4 times to select a cell
another bot i played with used two messages for a 5x10 grid, though they didnt edit one of the messages through the interaction directly so it hits the edit ratelimit pretty fast
how would i make my bot leave every server under 15 members
Loop over all guilds in bot.guilds and then check the total members, if lower than 15 make the bot leave the server. Reading and searching in the documentation will help to find the appropriate attributes and functions.
You can also use the event that is triggered when the bot joins a server - simply check again if the total members is below 15 and leave if it's the case - so that you won't need to do that manually in the future.
Define "interactions"
• Buttons are interactions
• Slash commands are interactions
• Modals are interactions
• Select menus are interactions
• ...
And what have you already tried?
If you've tried nothing then maybe you can try researching on your own using the documentation and looking at the examples here https://github.com/Rapptz/discord.py/tree/master/examples
yes = discord.ui.Button(label="Yes")
async def yes_callback(i: discord.Interaction):
nonlocal execute
execute = True
yes.callback = yes_callback
no = discord.ui.Button(label="No")
async def no_callback(i: discord.Interaction):
nonlocal execute
execute = False
no.callback = no_callback
view = discord.ui.View()
view.add_item(yes)
view.add_item(no)
await ctx.send(ctx.author.mention, embed=embed, view=view)
ok so uh
i have a message that just asks "yes" or "no"
if "no", deletes the ask message and yeah yeah
if "yes", performs the action
pretty simple, but i've no clue how to actually do it
[...] and looking at the examples here https://github.com/Rapptz/discord.py/tree/master/examples
kk
is there a more "quick-n-dirty" way to do it?
don't wanna make an entire class just for confirmation
That is the way of doing it
bluh
should I use try/except in commands?
You can, I'd rather use appropriate error handlers
Because you maybe don't want to have always the same try/except when you can put it in one single global handler
it's a specific error
Yeah then as said, you can use them
so I am running a boost bot but I am getting this erorr and the server id for KeyError is right i double checked anyone know why?
Well, key cannot be right otherwise you wouldn't get that error...
Furthermore, without code we can't help properly but just take random guesses
How do I get my bot to store an if statement trigger as a variable?
Because people can roll dice right now but they can’t add any modifiers.
And I want to make it so it’s possible to add modifiers in the same message.
So even if they roll d20 or a d20+1 it calls the same if statement but calcs it differently depending on if there is a + or not.
so you want me to send a valuable source code in a discord public server? is there a way I can just send it in your dms?
How is that valuable code?
There's nothing secret just using public library
people sell the code for $100

im serious
Selling for 100$, pathetic
some othes sell for $60
Whatever, share only the part where the guild ID is used
Probably like 1-2 lines
I was planning on using regex if possible.
The entire code can most likely be copy pasted from some random GitHub repository for free
its used 24 times in the code
Then where it's linked to that specific error
Or maybe I could add a nested if statement?
Otherwise yeah, shoot me a DM I'll take a look in some time
wdym
its a boost bot tho
Make sure you put IDs as integers, not strings
also whatever update_guild_commands is probably doesn't work
That's in the library itself
dpy? no its not
Read the traceback
It's internal code within the library
Nothing user controlled
there is no traceback relating to what that function actually is. the only info from the traceback is all dpy stuff lol.
And that's my point
They are using guild IDs somewhere that is used by that function
Since they wrote it wrong, it errors within code from the library itself
So yes, update_guild_commands works perfectly fine
@slate swan do you know if there is any way when an if statement is used to store the message that started the if statement as a variable?
no its not i double checked

you sure?
Yeah it's internal
As said countless times
these are the only two places where update is written
its literally dpy
Guess I turned on invisibility or something.
Yeah that's jot the issue
The issue is that you're using guild IDs incorrectly
As said, make sure they are integers and not strings
hmm
I'll look at your code in some minutes
I know my question is probably pretty basic but to not even validate a response is just cold.
If nobody responds either nobody CAN or you have not asked in a way that is understandable with examples or similar.
Not responding if people can't is not being cold, it's just not sending random pointless messages that flood the chat
Not with parameters like these I suppose
I haven’t set the library call yet.
The idea is for it to store the initial message sent that activated the command.
Then I am going to try and use regex to split the message into two parts.
Then use the second part and apply it as a modifier to the base result.
But the issue is I don’t know how to do that first part.
@slate swan
config.json
"guildID": "1018396160274223124"
guild_ids=[settings["guildID"]]
As said, IDs are integers - so remove the quotes from the JSON so that it's an actual integer and not a string
Has been changed to that quite some time ago
when was it changed if you dont mind me asking
Well, you can simply use the on_message event and then execute the command accordingly with the modifiers that you've parsed before.
I'd say approximately 4 years ago
im getting this now
damn so the guy sold me a really old bot
is it even worth it fixing it?
Well not so old since it uses slash commands
Just non tested code
Though @bot.slash_command never existed or is old code before v2.0
So I wouldn't really bother fixing the code, as you'd most likely need to rewrite almost everything as it's super old and unsupported code
hmm
You need to define bot.session = ... somewhere, take a closer look at the bot, RoboDanny, you've copied this code from they most likely have that somewhere
bot.py line 123
self.session = aiohttp.ClientSession()```
how can i check the date of the code?
No way of really checking it to be honest
then how did you find out that it was written 4 years ago?
Was a guess, because IDs got changed from string to integers approx 4 years ago and in the code strings are still used
Actually you got completely scammed but yeah
The code is public
So you got sold something you can download for free on GitHub 
The channel is not in the bot's cache
Hence you need to use something like
c = interaction.client.get_channel(...) or await interaction.client.fetch_channel(...)
So that it will first try to get the channel from cache, otherwise fetch it with an API call
Exactly, only the first part of the code
The or is part of Python
It's not "do that or that" in english
Python will try the first method, if returned None will use the second part
As the second part is only needed to be used if the first part resulted to None
Correct, should do the trick


So looks like the code you've shown in red, will only be executed when executing the command
You'd need a on_message event and check within that event if the user was AFK
Can't you directly select the reason?
And forget about the SELECT userID FROM ...
Then if it found something in the AFK table, send a message saying the user is AFK
I'd just use a SELECT reason FROM afk WHERE ...
Basically just keep the lower part and remove the part above
Basically, just make a query to SELECT reason FROM afk WHERE ...
If it found something, send a message
Otherwise, do nothing
Remove everything related to AFK and recode it, with what said above
You will figure out what needs to be kept and what needs to be removed
My guess is that you just need that part
Then if it found something, send a message
And I recommend you to one day switch at using cogs, so that you don't have a 4k+ lines bot.py file
Things that are not needed, yes
Keep things like async with ...
As these are needed for the database connection and queries
I'll go back at working 
That is not necessary anymore
The else at the bottom is wrongly indented
Should be
if result1 is None:
return
else:
# Send your message here
Or, you can just do
if result1 is not None:
# Send your message here
Inside the if you can keep them
The if (member1.id, ) in member is not necessary anymore
So you will need to fix the indentation
member1 = message....
await cursor.execute(...)
...
if result1 is not None:
# Send your message here
That's about all you need
The else is wrongly indented, should be same level as the if
Like that
Right now you're sending the message if there was no member mentioned in the message
And result1 is not defined in that scope, so it should error at the moment
Indenting it accordingly will do the trick
Yeah that looks better
Is it possible to get the data of all of the messages sent by a person in another server as a csv or something similar?
It is, though that seems like against Discord's Developer Policy
That case use some print to see where it stops, ignore the lower part for now
In your SQL, use userID={...}
Not sure if that will fix, but I remember having issues with that myself
3956
And also message.author.avatar.url for 3967
!sql injection
SQL & f-strings
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.
Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.
For example, the sqlite3 package supports using ? as a placeholder:
query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)
Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.
See Also
• Extended Example with SQLite (search for "Instead, use the DB-API's parameter substitution")
• PEP-249 - A specification of how database libraries in Python should work
To my knowledge, a user ID cannot be changed by users to anything they wish - nor a guild ID.
No, you have userID = {...} and not userID={...}
Though you should get errors
Nonetheless use some print to debug where your code doesn't work as intended
Yeah ignore the welcome back for now
Focus on the part above
The part below will never be executed because of that
And you need to indent it outside of the if len(message.mentions) > 0 as you also want to send the welcome back message if there was no member mentioned in a message
Remove it
if message.guild is None:
return
if len(message.mentions) > 0:
member1 = ...
[...]
# Your welcome back code
await cursor...
[...]
Indented one more to the left
Currently you will only execute the welcome back code if there was a member mentioned in a message
Yeah like that
Also I do believe that
if message.guild is None:
return
is not needed at all
As you already similar above
Don't need the lavender part
Correct
Well, any errors? Any prints not executed which should be? etc. etc.
Ah yeah
That is printed though
Is that getting printed?
Yeah, enable the message_content intent
!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.
Do you have all of the intents enabled? Or you're having multiple on_message events?
No need of the members but the message_content is needed
In code and developer portal?
Then check if you don't have other events of the same
If he's not going to use the message's content, he won't need it
!d discord.Intents.messages
Read. the. code. They are using the content
Whether guild and direct message related events are enabled.
This is a shortcut to set or get both guild_messages and dm_messages.
This corresponds to the following events...
!d discord.ext.commands.Bot.listen - Then use bot.listen instead
@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/latest/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...

Now consider using cogs 
Sure, gonna take my break
Bot doesn't have the permissions to edit members
Bot is trying to edit the nickname of someone it can't edit
You're probably owner
Test with another account
Oh yeah and when selecting the reason for AFK etc. consider also checking for the guild ID and not just the user ID
So like SELECT reason FROM afk WHERE userID={...} AND guildID={...}
So that you get the AFK reason of the user in the current guild
I'd rather use message.guild.id
Other than that seems fine
Errors or they are gone now?
Yeah the bot still doesn't have the permissions to edit the nickname of the user
As I said, create a new account and use that one for testing
are you checking for AFK using the username? lol
No
The bot still will never have the permissions to edit the nickname of the owner of the server
Create a new account and use it for testing, takes 60 seconds to create an account
Or yeah, don't edit the nickname
And in your DELETE statement at line 3973, remove the whitespaces
userID={...}
Yeah remove it for now, you can always add it later again
In your select at 3969 also check for the guildID
You probably have an AFK status in another guild ID and since you're not selecting for the specific guild it will always return one

Shouldn't take too long, go on
Right, so one issue is that you're adding the reaction to msg
And you're overwriting message
So remove lines 3823 & 3824
And add the reaction to message
Which is the case right now
And when using
async def on_message(message):
don't create variables like msg or message in your code, keep it clear which variable is what
Yeah, that's not needed
Correct
And when you send a message and want to delete it after some time, use
await message.channel.send("Hello world", delete_after=5) # Will be deleted after 5 seconds
Correct
You can also delete these two
Just replace with await message.delete()
As that will delete the original message sent by the user
That is also unnecessary, just put the emoji directly in the parentheses
Yeah, so that you keep the same format as your other events
I'd rather replace every msg to message
as you've used that before in other events
To keep consistency
No need of the .delete()
No need to assign it to a new variable either now
After that check the current status
And yeah, remove the whitespaces in your queries
number=...
3824
Yeah, since you used delete_after
Sure
And use some print if to debug as always
remove whitespaces and add some print
Yeah that error is kind of normal
See at line 3807 you're checking if result2 is none
If it's none, then at line 3809 you're getting the index 0
Which will never work as it's None
Don't understand what you're checking there
You can also remove line 3810 and 3811 as you already have that at line 3786 and 3787
Well, if result2 is none then you just want to insert and react accordingly
You don't want to update, don't want to check if the user was the same
if not result2:
# Check if it's "1" then insert and react accordingly
else:
# Check if playing alone, update and react accordingly
Just put everything else than insert stuff outside in an else
Put the if result2[0] == message.author.id and if result2[0] != message.author.id in a new else statement
if not result2:
# Insert stuff
else:
if result2[0] == message.author.id:
# Your stuff for playing alone
else: # Same as 'if result2[0] != message.author.id'
# Your stuff for updating and reacting
Line 3809 to 3814 should be in the else
There is no reason on checking if they're playing alone when it's the first message sent
You also don't need
alone = ...
await alone.delete()
just do await message.delete()
in the
else
Not outside of it
And in your insert
You probably want to insert number as well
And set it to 1, unless you've added a default value in the schema
if you've set a default value, which you should, that's fine
Yeah
line 3822 is elif though
where you insert
No need of an argument
First number is always 1
3823 also elif
Small off topic question, have you even learned Python
No need to read the docs for basic Python
I won't, just been wondering
That case I recommend learning more
Yeah so about that, just insert 1 directly instead of using %s
Yeah probably better, remove number though at 3806
Yeah that one
Yeah because you probably have old rows in the database
Need to clean that up
If it's hosted somewhere there's most likely an online management system you can use
What is even ApplicationContext
Doesn't exist in discord.py
Ah okay, weird decision
Well that case it's ctx.user or ctx.author not ctx.member
They have a python sdk and documentation at https://docs.top.gg
I'll eat
A bit off topic but like really?
You haven't seen mine
Something like 15k+
It only took like 3 weeks to fix the bug causing the entire bot to crash when a command that uses anything that can only be done in a guild in DMs
Look the positive side: You fixed it
yea
I just realized
I need someone without permissions to run a command
mine's over 200k :kek:
There's a 0 too much here
You're using fetchone()
So it will always return only one
Yeah pretty much
it will return all
Well that's normal
You need to loop of the results now
As you don't have only one result
A for loop over the results
for x in y:
x[0] # First column of each result
Well y needs to be a list
item returned by .fetchall
No
fetchall() returns your list needed
So loop over that
Then you need to append the role to a string or new list to be able to display them all in the embed at once
!e
y = [1, 2, 3]
z = ""
for x in y:
z += f"{x}\n"
print(z)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1
002 | 2
003 | 3
That's when actually knowing Python becomes handy
Copying code won't help you in learning
z = "\n".join(y)+"\n"
error.
z = "\n".join(map(str, y))+"\n"
As far as I remember, [1, 2, 3] is not a list of strings
Yeah, and that's absolutely horrible
ok
Make your entire file a one liner to make it look cool at this point
y is there list builder and no string builder
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
didn't knew py
ok
get_member is not a coroutine, so you don't await it
how do i make selected images, when run the command, be randomly sent?
inside the parentheses?
Yeah x2
by url?
When do we use fetch_member and get_member? Do they have their own uses?
You can give anything you want, can give a list of string URL or a list of objects doesn't matter
fetch_member should be used if get_member returns None
get_ gets from cache, if it's not in cache it will return None
fetch_ makes an API call
Yeah, but pass a list
Explain.
Ty and will fetch cache the member if it's called?
!e
import random
x= ["url 1", "url 2", "url 3"]
print(random.choice(x))
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
url 2
More basic python knowledge is not doable
thanks
if you have member intents then it should, else it won't
^
Thanks
Usually doesn't really matter as you'd use
x = get_xxx(...) or await fetch_xxx(...)
👍
x= ["<https://tse2.mm.bing.net/th?id=OIP.5Ks1dLss5GbwhfKPee1yjAHaE8&pid=Api&P=0>", "<https://tse1.mm.bing.net/th?id=OIP.Ly8dLGPXJ5mx3aVw88mUKgHaE1&pid=Api&P=0>"] await interaction.response.send_message(f"", ephemeral=False)
I did, how do I put it to send in chat?
@slate swan
!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.
Once again, most basic and fundamental knowledge
Need better/longer traceback
You're trying e.g. x[0] on a SlashCommand object
sorry, iam from brazil
Well
Most likely because you have a slash command named list
Which is a reserved keyword
And should not be used for function name e.g.
Otherwise you overwrite it and that's not good
Just name it job_list
That's fine, just don't have a function or similar named list
Good
@bot.commands(name="list")
async def job_list()
Not good
@bot.commands(name="list")
async def list()
Yeah - change list to job_list
And you can set name="list" in the decorator as shown above
I'd usually recommend to use job_list etc. for every command
You might have one day for example items list command
So you can't name it just list as well
Instead it would be items_list
To keep it unique

class system(discord.ui.View):
def __init__(self, user):
super().__init__(timeout=None)
self.value = None
self.timeout = None
self.user= user
@discord.ui.button( label="Other Games", style=discord.ButtonStyle.blurple, custom_id="other_games:blurple")
async def system(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message(view=TicketView)
class TicketView(discord.ui.View):
def __init__(self, user):
self.user= user
super().__init__(timeout=None)
@discord.ui.select(placeholder="Choose a role!", options=[
discord.SelectOption(
emoji="", label="Counter Strike", description="Choose me if you want to be updated when someone wants to play CS!"
),
discord.SelectOption(
emoji="", label="Valorant", description="Choose me if you want to be updated when someone wants to play Valorant!"
),
discord.SelectOption(
emoji="", label="Haxball", description="Choose me if you want to be updated when someone wants to play Haxball!"
)
])
async def help_callback(self, interaction: discord.Interaction, select):
select.placeholder = f"Reason: {select.values[0]}"
reason=select.values[0]
if reason == 'Counter Strike':
role=get(interaction.guild.roles, id=1030085444534292560)
if role in interaction.user.roles:
await interaction.user.remove_roles(role)
else:
await interaction.user.add_roles(role)
await interaction.response.send_message(f"Chooses Counter Strike Succssesfully!", ephemeral=True)
if reason == 'Valorant':
role=get(interaction.guild.roles, id=1008808500744441876)
if role in interaction.user.roles:
await interaction.user.remove_roles(role)
else:
await interaction.user.add_roles(role)
await interaction.response.send_message(f"Chooses Valorant Succssesfully!", ephemeral=True)
if reason == 'Haxball':
role=get(interaction.guild.roles, id=1030085098600669195)
if role in interaction.user.roles:
await interaction.user.remove_roles(role)
else:
await interaction.user.add_roles(role)
await interaction.response.send_message(f"Chooses Haxball Succssesfully!", ephemeral=True)
@bot.command()
async def sys(ctx):
view = system(ctx.author)
embed=discord.Embed(title="**רוצים לדעת ראשונים כשמישהו רוצה לשחק?**", description="מוזמנים לבחור אחד מהרולים המופיעים כאשר אתם לוחצים על הכפתור! \n תהנו!")
embed.set_footer(text=f"Requested by {ctx.author}")
await ctx.send(embed=embed, view=view)```
and when i tap on the button
```[2022-10-13 15:14:01] [ERROR ] discord.ui.view: Ignoring exception in view <system timeout=None children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Other Games' emoji=None row=None>
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "c:\Users\PC\Desktop\Among Us IL Bot\main.py", line 224, in system
await interaction.response.send_message(view=TicketView)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\interactions.py", line 703, in send_message
params = interaction_message_response_params(
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\webhook\async_.py", line 578, in interaction_message_response_params
data['components'] = view.to_components()
TypeError: to_components() missing 1 required positional argument: 'self'```
what do i do then
oh i will try
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Among Us IL Bot\main.py", line 273, in sys
view = system()
TypeError: __init__() missing 1 required positional argument: 'user'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Among Us IL Bot\main.py", line 168, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() missing 1 required positional argument: 'user'```
await interaction.response.send_message(view=TicketView)
Have you tried adding () after TicketView
Just like you do on the sys command
OH
i will try
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Among Us IL Bot\main.py", line 273, in sys
view = system()
TypeError: __init__() missing 1 required positional argument: 'user'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Among Us IL Bot\main.py", line 168, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() missing 1 required positional argument: 'user'```
Yeah change back to view = system(ctx.author)
That was correct
okay
now when i tap on the button it shows
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "c:\Users\PC\Desktop\Among Us IL Bot\main.py", line 224, in system
await interaction.response.send_message(view=TicketView())
TypeError: __init__() missing 1 required positional argument: 'user'```
Oh yeah haven't seen
TicketView requires an argument
So like system(ctx.author)
ohhh
ill try
Just ctx.author won't work as ctx is not defined up there
yes
interaction
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "c:\Users\PC\Desktop\Among Us IL Bot\main.py", line 224, in system
await interaction.response.send_message(view=TicketView(interaction.author))
AttributeError: 'Interaction' object has no attribute 'author'
its interaction.user
interaction.user
oh oops
author is implemented by some forks, dpy doesn't have it :p
tho author would make more sense imo ( since its an Union of Member and User)
how do i make it ephemeral
ephemeral=True when sending the message
oh okay
it all works
thank you all sm!
what error?
await interaction.response.send_message(embed=embed,ephemeral=True)
guild = interaction.guild
category = discord.utils.get(guild.categories, name="Test")
channeel = await guild.create_text_channel(f"etst-{interaction.user.name}", category=category, topic=f"test id/{interaction.user.name}")
``` any idea why it's not creating a text channel
(inside a button class)
Is there any way I can take it off?
yes
how?
right click on ur code and click on sort imports
it will change the order of your imports to the one following pep8
any idea guys?
thanks, work!
does the part of code get triggered?
add some print statment to verify
No need of print statement
If the embed doesn't get send, it most likely doesn't reach the code 
it's not getting triggered
Then there's something wrong above/before, and not there
❌
only the create channel is not getting triggered
all other functions are getting triggered
first imports of stlib, then from imports of stdlib
then same for external libs
Been awhile I've visited this server.
So, well. What I'm trying to do here is if the author reacts to the bot message (Sent after executing the cmd), it will send the respective embed. But this one doesn't work? Is there any alternative ways I can go about this? (This isn't the full code but yeah, it's basically what I'm trying to do)
if Ten in RandomBellResult:
TenResponse = await ctx.send (embed=EmbedInput)
await TenResponse.add_reaction("")
if str(Reaction.is_custom_emoji) == "":
await ctx.edit_message(Embed=TenEmbedOutput)
There are like multiple embeds for this. I'm making a command, similar to OwO's ,bell cmd
Like this
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
Btw, what does check do?
check (Optional[Callable[…, bool]]) – A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for.
ALright. Noted will keep these in mind. Thanks! 
Why are you calling the command in the middle of an embed?
Remove the call to that command
Idk what that function does or need
You will run in an endless loop if you call it
You're calling the command again
Don't do it
As it will call the command over and over and run in an endless loop
Yes
Yeah, because your function to get the list of jobs should be named differently and called again
Not job_list
As that's the name of the function for your command
get_jobs_list might be good I suppose
Then you can call it like before with + await get_jobs_list(interaction, 1) if you have the same function arguments as you did before
Codes
Nvm its ik
Ok
I'll go on my way home and then rest a bit, ask here and someone else may help otherwise I'll check out when I'll be back
Send man
- you need to optimize your code
Theses get channel definitions and if elif statements is to much
Section of code that got the error
elif Hundred in RandomBellResult:
HundredResponse = await inter.send (embed=EmbedInput)
await HundredResponse.add_reaction("")
def check(reaction, user):
return user.id == inter.author.id and str(reaction.emoji) == ""
try:
reaction, user = await self.bot.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await inter.send('👎')
else:
await inter.edit(Embed=TenEmbedOutput)
Error:
Ignoring exception in command bell:
Traceback (most recent call last):
File "C:\Users\Shuma\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\core.py", line 172, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Shuma\Desktop\Programming\VS Code\Neko-Nyan\Random\TestCmds.py", line 201, in Bell
await inter.edit(Embed=TenEmbedOutput)
AttributeError: 'Context' object has no attribute 'edit'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Shuma\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\bot_base.py", line 578, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Shuma\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\core.py", line 914, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Shuma\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\core.py", line 181, in wrapped
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'edit'
What am I doing wrong here?
I'll probably be sleeping soon so ping me if replying
how do you fetch a guild by it's id inside a button class?
interaction.get_guild doesn't work
nor does client.get_guild
!d discord.Interaction.guild
property guild```
The guild the interaction was sent from.
get_guild doesn't work?
nope it doesn't
what lib?
Guys how can I make a !d command like @unkempt canyon in dpy?
Go by yourself on the website, it doesn't exist (anymore)
Pls help anyone
Look at the code and get inspiration, it's open source... (Read the bot's 'about me')
That code is very hard to understand
Isn't after.roles and before.roles already returning Role object?
Why would you try get the role again
Just use the roles that the after return?
Do you really have to ask
async def change_status(*args, **kwargs):
guild = bot.get_guild(246691336776843265)
membercount = guild.member_count
await bot.change_presence(status=discord.Status.dnd, activity=discord.Activity(type=discord.ActivityType.watching, name="{} members".format(membercount)))
await sleep(10)
await bot.change_presence(status=discord.Status.dnd, activity=discord.Activity(type=discord.ActivityType.watching, name="Noazx#0001 Developer!"))
@bot.event
async def on_ready():
change_status.start()```
im trying to make the status change and that doesnt work
my bot stopped working after the API update. What should i do?
Which API do you use? What errors do you get?
OH NVM
Btw you could just use loops instead of manually mentioning the discord activity
its working
he's using a loop in a weird way
im a girl
status = [
f"humans in {data['guilds']} Servers!",
".help / dot help",
f"{data['users']} users!"
]
while True:
for i in status:
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=i))
await asyncio.sleep(120)
This is what I use, maybe you could take some inspiration from it?
ok sorry
that's shit too, why you need to use asyncio.sleep if it's a tasks.loop?
Actually it's not
python and the errors are relalting to intents
reread well
I'm going to use task.loops but for now I'm using a function which has that and I'm calling it on on_ready (ik that it's not a good practice)
intents is a required positional argument that you need to pass while creating a Bot or Client object
!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.
you can't send an embed when defering an interaction
you need to first defer and then to edit the original response
your code is so messy
btw have you saved the changes?
also ctx is ctx and interaction is interaction, you shouldn't use ctx to represent an interaction, they works in different ways
look at your code lmao
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
I recommend you read the kwargs the method can accept
I mean look at your function, you're using ctx everywhere to represent an interaction object
listen function is not working, there is some problem relating to intents
can someone help me out?
yea, what's your problem?
listen function is not working, there is some problem relating to intents
which event you're listening
default
to be fair, thats how pycord writes it in their examples, and the actual object given to the slash command is called an ApplicationContext
https://docs.pycord.dev/en/stable/api.html#applicationcontext
https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_basic.py#L20-L23
examples/app_commands/slash_basic.py lines 20 to 23
@bot.slash_command(guild_ids=[...]) # Create a slash command
async def hello(ctx: discord.ApplicationContext):
"""Say hello to the bot""" # The command description can be supplied as the docstring
await ctx.respond(f"Hello {ctx.author}!")```
I didn't think he was using pycord since he didn't specify it I thought he was using Discord.py
i made the assumption of pycord based on the @slash_command decorator and the discord namespace in their traceback
can you show the code that isnt working, and also the name and version of the library you're using?
how do i make my bot read messages after the intents update. I don't know what has happened after the update
!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.
Enable the message_content intent, that's it
WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected. what do i do?
Exactly what is written above
- Enable the intent in code
- Enable the intent in developer portal
how do u enable it in code?
See above, for the third time
Still hasn't changed in-between
See message above, once again
One more person that cannot read, wonderful 
I believe I clearly wrote
message_content
so i wanna make an event that if member says something on a channel it deletes the message and turn it into an embed, how do i do that?
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
oh yes thanks
How can i create / cmds ? Can someone show me an example?
is there a way to edit a regular message thats not a response
!d discord.Message.edit
await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
thanks
how to delete an ephemeral message in nextcord after an interaction with its view button?
Bots can't delete ephemerals iirc
Exactly
where
u can't use .response multiple times
Pretty sure you can't
can't sorry
Use followup
but why... just check if rate is inside a list or something, all of those ifs look very messy and are pretty pointless if you're doing the same thing regardless of the value of rate 
I prefer to make code that I understand how it works
But I cant start the bot. I dont get any error .
import discord
from discord import app_commands
from discord.ext import commands
class MyCog(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@app_commands.command(name="command-1")
async def my_command(self, interaction: discord.Interaction) -> None:
""" /command-1 """
await interaction.response.send_message("Hello from command 1!", ephemeral=True)
@app_commands.command(name="command-2")
@app_commands.guilds(discord.Object(id=922642978940526653))
async def my_private_command(self, interaction: discord.Interaction) -> None:
""" /command-2 """
await interaction.response.send_message("Hello from private command!", ephemeral=True)
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(MyCog("TOKEN"))
example please
if rate == "2":
await inter.response.send_message("Dziękujemy za opinię!", ephemeral = True)
embed = disnake.Embed(title = "Opinia", description = f"{osoba} ({osoba2})\n\n:gwiazdka:\n\n{textValue}", color = 0x2f3136)
embed.set_image(url = "https://cdn.discordapp.com/attachments/1018592616226496568/1020638078844555295/luckyTest.png")
await inter.channel.send(embed = embed)
if rate == "1":
await inter.response.send_message("Dziękujemy za opinię!", ephemeral = True)
embed = disnake.Embed(title = "Opinia", description = f"{osoba} ({osoba2})\n\n:half:\n\n{textValue}", color = 0x2f3136)
embed.set_image(url = "https://cdn.discordapp.com/attachments/1018592616226496568/1020638078844555295/luckyTest.png")
await inter.channel.send(embed = embed)
else:
await inter.response.send_message("Wpisałeś złą wartość! Pamiętaj, że ocena musi być w przedziale od 1-10", ephemeral = True)```
you're passing a string (your token) to a field that requires a Bot instance
instead of inter.channel.send, use iter.followup.send
okay let's try
Were should i set my token?
I dont think there followup in disnake
Never seen that before 🤷🏾
lmao followup exist in disnake
!d disnake.Interaction.followup
Returns the follow up webhook for follow up interactions.
I think it would be pretty stupid if it didn't have it lol
I see now
btw it's better to use inter.send as it automatically handle response or followup
wherever you call bot.run/bot.start, that's probably the only place that your bot token will be required
yo anyone know how to handle parameters from message content? its for a good reason not just a case that i dont know how to use commands
Probably some external library to parse parameters from a string correctly
One that would interpret !say "Hello world" yes as 2 parameters
- Hello world
- yes
Otherwise make your own parser
ye exactly
shlex.split or commands.view.StringView (undocumented) would be good alternatives for that
Oh shlex also exists on Python nice
shlex seems like the one, you are a god - thanks.
Yeah then I recommend shlex as I use an implementation of that for my projects
Didn't know Python also had shlex
i never knew about shlex, whats its overall usage?
🤷 I've only used it for string parsing
Well string parsing
oh
dope
The shlex class makes it easy to write lexical analyzers for simple syntaxes resembling that of the Unix shell. This will often be useful for writing minilanguages, (for example, in run control files for Python applications) or for parsing quoted strings.
TL;DR string parsing 
Other, more understandable, description
A simple lexer which splits input in tokens using shell-style rules for quoting and commenting.
ty
@fading marlin you are amazing - thanks.
['hello there', '123123', '132', '123', '123'] 
Anytime! 
yo ctx.invoke
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=context#discord.ext.commands.Context.invoke
supports *args and **kwargs, how do i send them like that yk
can i just submit a list instead of seperating them?
found it i think
You can use the * to unpack a list, e.g
some_list = [1, 2, 3, 4, 5]
def function(one: int, two: int, three: int, four: int, five: int) -> int:
return sum((one, two, three, four, five))
function(*some_list) # returns 15
No problem!
talking about lexical analyzers i'm currently implementing one to my compiler🥲
yoikes good luck for that
Thanks
me neither, i just want to implement a language for experience and it's not going to be domain specific which makes the matter worse

.
😔
Guys does anyone know how to recreate this effect? With the dark outline around the text, and the green border?? I need a discord bot to send text that looks like this :P
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...
Oooh okay.
Thanks :D
Sure thing
:D
Can I assign a role to someone with just the ID?
Tried await message.author.add_roles(role.id==12345...) but it says I still need a name
you should be able to pass in a snowflake
await message.author.add_roles(discord.Object(id=12345))
Ah alright. Thanks
yup
`Traceback (most recent call last):
File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\app_commands\commands.py", line 862, in _do_call
return await self.callback(interaction, **params) # type: ignore
File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\comandos.py", line 94, in clear
await inter.response.send_message(embed=msg, ephemeral=True)
File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\interactions.py", line 762, in send_message
await adapter.create_interaction_response(
File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\webhook\async.py", line 218, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\app_commands\tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\app_commands\commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File `
this log is from a clean chat code, it cleans but doesn't show the embed, what's wrong?
@commands.has_permissions(administrator=True)
async def activity(ctx):
msg = await ctx.send("**Activity Check**\n\n@everyone")
await ctx.message.delete()
await msg.add_reaction(':Check_Mark:')``` I haven't coded in months I am trying to re learn so yea
its slash command?
nah
bruh
what is the python version that you're using?


