#discord-bots
1 messages · Page 98 of 1
i use nextcord, so i dont have an discord.py package
then how u trying to import from discord
Oh, well
isn’t their whole thing replacing discord with nextcord
You can use nextcord's example in that case
https://github.com/nextcord/nextcord/blob/master/examples/modals/modal.py
A Python wrapper for the Discord API forked from discord.py - nextcord/modal.py at master · nextcord/nextcord
they use the discord namespace too
alr
gotcha
Thanks, worked
Hello, good morning, guys, I'm not sure how I can handle this, I'm new to python and I'm coming from JS
['1\n7\n9\n21\n8\n14\n7\n21\n24\n1\n2\n31\n19']
I'm trying to use split.. text.split('\n/g'))
The split function doesn't take regex
Removing that /g should fix it, because currently it's splitting based on the literal "\n/g" delimiter
Thanks, I didn't know it didn't work, because as I would use it in JS, I would think it would work in Python too. Thank you ❤️
No problem <3
re.split takes regex split functions.
They did not specify that they were using the re module
!d re.split
re.split(pattern, string, maxsplit=0, flags=0)```
Split *string* by the occurrences of *pattern*. If capturing parentheses are used in *pattern*, then the text of all groups in the pattern are also returned as part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* splits occur, and the remainder of the string is returned as the final element of the list.
```py
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
I guess that helps too, though
They aren't but you can split using regex.
@granite sun
Splitting with regex here will be slower than using str.split and using regex also means you need to import re when there is no point
In [2]: %timeit -n10000000 '1\n7\n9\n21\n8\n14\n7\n21\n24\n1\n2\n31\n19'.split("\n")
211 ns ± 1.47 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
In [3]: %timeit -n10000000 re.split(r"\n", '1\n7\n9\n21\n8\n14\n7\n21\n24\n1\n2\n31\n19')
866 ns ± 15.4 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
``` and by a lot too
@bot.event
async def on_message(message):
handle = await aiofiles.open(f'{message.guild.id}.txt', mode='r')
data = await handle.read()
if str(message) in data:
await message.delete()
handle.close()```
why is this not working?
I have the word "cheese" in the txt file
but It still doesn't wor
!d discord.Message.content
The actual contents of the message. If Intents.message_content is not enabled this will always be an empty string unless the bot is mentioned or the message is a direct message.
where can i find the discord_component lib ?
async with aiohttp.ClientSession(headers=headers, connector=None) as session:
async with session.patch(f"https://discord.com/api/v10/guilds/{ctx.guild.id}/",json={"name" : "test"} ) as r: ```
Getting error of 404 not found
Help
Send code
?
On button callback
....
and why you friend request me
@feral frost just wanted to increase frnds
What is a "1+1" task?
ye like i click a button with 1 on it and a button with + on it and the button with 1 on it again and i want the output to be 1+1=2
🤔
You subclass view, create 3 buttons, and store the currently clicked button's state and bind it to the view subclass. And on each button click, depending on the state, you send 1+1=2 or update bound state
a calculator you mean
ok you know how ?
yes but i wanna begin simple
Yeah, see the message I sent
How... what? I just gave you instructions
Ah, I see what you're saying
https://github.com/Rapptz/discord.py/blob/master/examples/views/tic_tac_toe.py this is a pretty complex example as far as examples go, but it's a complete example, hopefully it's a good starting point
ok ty
what robin said and maintain a string with the operation to perform
like a base string ```py
base = ""
on 1 clicked
base+= "1"
on + clicked
base+="+"
on 1 clicked again
base+="1"
theres better ways but this is the easiest i could think of
ah ok
wait how do i do the asts eval function ?
!d ast.literal_eval
ast.literal_eval(node_or_string)```
Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, `None` and `Ellipsis`.
This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.
how do i use it
hello ?
!e
import ast
print(ast.literal_eval("1 + 1"))
Sad
Just call it with the operation you want to execute
ok
Hey, it keeps getting stuck here. anyone know why?
https://i.leaked-your.info/xQ3LypaL
it says discord.py so its related to this
the issue isn't related to the channel even if it says discord.py. you might want to seek help in #python-discussion or claim a private help channel (see #❓|how-to-get-help)
Its not building discord.py right, how is that not related to this
it's not a discord.py issue though.
Clearly it is, because it works on my other bots thats running a older version
so guessing it is with the new push, and if i lower the version it will work lol
smh arguing with people is like arguing with fools walls
not trying to aruge, just stating the obious /shrug
obvious*
and right, I'll just step back
didnt know this was a spelling bee, and it was a discord.py issue 🧍
newest release of discord.py is broke with 3.10
withs with 9 and 11
Where is this being run? Inside a docker container?
Anybody know how I can make my bot post something once every 24 hours? I currently have it written to post a fact when someone uses -fact but I'd like that to happen on its own once every day.
Someone suggested using cron but that would just start the bot not prompt the bot to post something. Unless I made it so it posts on ready and stops the bot afterwards
use a task
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
Mine? Lol
yes
Thanks I'll look into this
I've had this username on all platforms since I started an Xbox 360 account lol
Idk 15? Years ago
Hey guys I created a mute command, but i don't know how to add the "mute" role to all text channels
I'm that old
yea
I had to think on it for a minute. 15 sounded like a lot of years for something as recent as the Xbox 360 but I just Googled and it came out in 05 so 15 is probably close 
would work
Yeah that works
But i don't know what to do, to add the "mute" commands to all channels
I've been looking the docs and tried to use Textchannel set permissions
it does automatically (it won't if you have messed up with overwrites)
mmm imma look into it
no
it's not that, cuz i did the exactly same thing by hand without the bot
and it's the same, so you must add that muted role and set it on text-channels too
Using discord webhooks, is it possible to tag someone or role?
yes, iirc you should pass allowed_mentions kwarg
are u using discordpy?
Don't worry figured it out. and i am not using discordpy. I am using webhooks.
Just put the id betwee <@ >
for example: @drifting arrow
Yeah, same way regular mentions work
I've always just done the default mention thing lol
in discordpy. never had to think about it
discord/user.py lines 246 to 249
@property
def mention(self) -> str:
""":class:`str`: Returns a string that allows you to mention the given user."""
return f'<@{self.id}>'```
Anyone knows how to remove send_messages in Text_channel for a specific rol?
i want to create a role check how can i crate ?
my try
def check3(m):
role = m.guild.get_role(m.content)
return role in m.guild.guild_roles```
who uses oracle cloud
!d discord.Guild.create_role
await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., display_icon=..., mentionable=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") for the guild.
All fields are optional.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this.
Changed in version 1.6: Can now pass `int` to `colour` keyword-only parameter.
New in version 2.0: The `display_icon` keyword-only parameter was added...
role check not role
i got u
if discord.utils.get(user.roles, name="MHT access III"):
nope its a wait_for check
bruh
it will be a string input
def check(m):
return m.content and m.channel == channel and discord.utils.get(m.author.roles, name="Middle Man")
msg = await bot.wait_for('message', check=check)
await channel.send(f'!rename {str(msg.author).split("#")[0]}')
its like this basically
inside of check func u put ur condition
aa nope , i want to check , wather the wait_for message is a role or not
get my point ?
😐
just use this
with this
this is different
but thats how to verify if the name in a message is a role in the guild
ure gonna have to use these two things
async def create_balance(user):
async with bot.db.cursor() as cursor:
await cursor.execute("INSERT INTO bank VALUES(?, ?, ?, ?)", (0, 100, 500, user.id))
await bot.db.commit()
return
async def get_balance(user):
async with bot.db.cursor() as cursor:
await cursor.execute("SELECT wallet, bank, maxbank FROM bank WHERE user = ?", (user.id))
data = await cursor.fetchone()
if data is None:
await create_balance(user)
return 0, 100, 500
wallet, bank, maxbank = data[0], data[1], data[2]
return wallet, bank, maxbank
async def update_wallet(user, amount: int):
async with bot.db.cursor() as cursor:
await cursor.execute("SELECT wallet FROM bank WHERE user = ?", (user.id))
data = await cursor.fetchone()
if data is None:
await create_balance(user)
return 0
await cursor.execute("UPDATE bank SET wallet = ? WHERE user = ?", (data[0] + amount, user.id))
await bot.db.commit()
@bot.command()
async def balance(ctx: commands.Context, member: discord.Member = None):
if not member:
member = ctx.author
wallet, bank, maxbank = await get_balance(member)
em = discord.Embed(title=f"{member.name}s Balance")
em.add_field(name="Wallet", value=wallet)
em.add_field(name="Bank", value=f"{bank}/{maxbank}")
await ctx.send(embed=em)```
why isnt it workinhg
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 366, in balance
wallet, bank, maxbank = await get_balance(member)
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 343, in get_balance
async with bot.db.cursor() as cursor:
AttributeError: 'Bot' object has no attribute 'db'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 192, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python310\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\Python310\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: 'Bot' object has no attribute 'db'```
your bot doesn't have db attribute
that doesn't show a db attr in your bot class
the fact that you have a db file doesn't mean it automatically creates an attr for you
i did that elso
@bot.event
async def on_ready():
print(f"{bot.user.name} is online!")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print (e)
bot.db = await aiosqlite.connect("bank.db")
await asyncio.sleep(3)
async with bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXITS bank(wallet, INTEGER, bank INTEGER, maxbank INTEGER, user INTEGER)")
await bot.db.commit()
print("Database ready")
@silk fulcrum
First of all, you only add a db attr if the syncing has raised an error, and second is that you reeeeally shouldn't do it like that.
What you should do - is to subclass the Bot and do that db stuff in setup_hook
OH
Here's an example of that (here it's used to create client session and load cogs, but you can use it for a db)
https://gist.github.com/Master326486/6cf48c1ca0509b98e673451e356ba625#setup-hook
thank you so much!
By the way syncing in on_ready is also very bad, like almost everything in on_ready is bad at least because it's triggered multiple times.
Where you should sync is in the command (what I mean is you create a command to sync your slash commands), you could also use jishaku's sync command.
And you should only sync when some changes to the slash commands were made, for example a name or a description has been changed. Do not sync when you made changes in the main code of the command, only for the things that discord shows: names, descriptions, permissions, e.t.c.
@slate swan
Oh i understand yes i will try also, do you know how can i do like many files i want and connect everyone with each other so if i will run py main.py it will load all of them?
I guess you are talking about cogs
yes
I don't think there is a fresh example of doing cogs, because they were recently made async (in dpy 2.0)
In this example what I've sent about setup hook there is an example of making cogs (https://gist.github.com/Master326486/6cf48c1ca0509b98e673451e356ba625#setup-hook)
And here there is an example of making commands and stuff like that in a cog (don't look at how they load the cogs, it has changed, so do it as shown in first gist) https://gist.github.com/EvieePy/d78c061a4798ae81be9825468fe146be
Or if you want to make slash commands in cogs, then this gist: https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32
how do i run all of them
all of the files
wdym
like
all of the cogs?
yes!
when u host a bot on heroku or daki
and u upload the files with a db file
they script is unable to update the db?
i tried using oracle but theres an availability issue
You should've probably read what I sent.
The main file loads them all here:
async def setup_hook(self):
...
# Loading cogs
for cog in myCoolCogs:
await self.load_extension(cog)``` (<https://gist.github.com/Master326486/6cf48c1ca0509b98e673451e356ba625#setup-hook>)
oh hh
That will "run all of them" if that's how you want me to say it
thank you so much!
You're welcome
how do i use @tasks.loop(time=15:30:00) properly? looked at the documentation for it and cant seem to figure it out
second, minutes, hours, days
no time
use a class
and rununtilcomplete to call the class or asyncio
wtf
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
oh there is time
i mean a cog
got it working with loop(time=seconds) but i saw that is an option so i wanted to explore it lol
well it's datetime anyways
or like this
@bot.listen()
async def on_ready():
compareUpdates.start()
@tasks.loop(hours=1, reconnect=True)
async def compareUpdates():
not 15:30:00
i figured it wasnt 15
00 i just wanted something to throw in there
weird emoji but ok
is there some documentation on this for me to follow
i found it on github when browsing
I don't even know what you would need that for
to learn 😮
how would i know when i need it if i dont know what it does
or how to use it
@faint sapphire what does that do
task.loop to loop tasks
no, what does "use a class and rununtilcomplete to call the class or asyncio " do
i mean i meant this
like how is it different from this
@tasks.loop(minutes=5)
async def oh_god_so_good():
yesss()```
from the little bit of reading ive done it sounds similar to an event scheduler to run something at a specified time. i could be wrong but thats why i want to learn
I'm not even gonna talk about this code, and how bad it is. And, about tasks, I don't see anything different, you just added that if the cog is unloaded then it stops
i know, i rushed things
Yeah, it's a background schedule for your bot
for example you can change bot's presence every 5 mins
or smth else every <time>
yea i got that much but i wanna know about that time part as opposed to minutes or hours
I think it's pretty clearly explained in docs, that time should be a datetime.time object that represents a time, that this schedule should be executed at, for example every day on 2:22 PM
!d datetime.time If you don't know how to make a datetime.timeobj
class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)```
All arguments are optional. *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...
I have another problem
i have installed discord-components and i don't know why it sends me this error
from my understanding it wants (time=time(xx,xx,xx)) which is why i came here to ask, because that didnt work lol
say like a string is 5e712ecf-2fbb-4f37-a462-155917378803 , how would i check how many "-" are in said string and if it has less or more than four say that is invalid help me
who uses digital ocean
What's a good reddit community to release my discord bot to?
It's just a generic discord bot for any discord server
I just want as many people to have it as possible ;D
!e ```py
print("5e712ecf-2fbb-4f37-a462-155917378803".count("-"))
@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.
4
!d str.count
str.count(sub[, start[, end]])```
Return the number of non-overlapping occurrences of substring *sub* in the range [*start*, *end*]. Optional arguments *start* and *end* are interpreted as in slice notation.
Dont setup a basic logger
lmao what
?
doesnt make sense what u said
I'm pretty sure those are logging messages from the logger that was setup in discord.py's source, which if you setup a logger depending on the level it would listen to the messages of that logger and sent then into stdout/cout
it wont catch if its a bot
if message.author.bot or message.attachments or str(message.author.id) not in Admins:
return #exit function
elif content[0] == prefix:
print("entered")
Well anything else could've been true
true
should I enable these, idr understand the implications
idk what the point of enabling ipv6 is
if message.author.bot: return
elif message.attachments: return
elif str(message.author.id) not in Admins: return
elif content[0] == prefix:
print("entered")
``` still
nvm im stupid
Lol
Hey guys, how can I revoke the permission to see a text channel with my bot. My bot already gives the user mentioned the "muted" role and restrict it, but obviously not in text channels. What can I do?
Why not use the built in timeout?
wow, i didn't look into it till now, thank u!! I'll look more
Hi, I'm new to coding and im just trying to get commands to work can anyone help me? This is what I have and it gives me no errors but doesn't work. I think its a problem with intents but i dont know how to fix it
Response: fzSftp started, protocol_version=11
Command: open "root@IPaddress" 25061
Error: Connection timed out after 20 seconds of inactivity
Error: Could not connect to server
when trying to use filezilla with a ubuntu vps on digital ocean
anyone able to help?
its not possible to use filezilla when using ssh?
i have to change it to a password authentication?
Can someone help me with pyqt? there #help-lemon PLS!!!!
guys can someone help me on how do have multiple commands in a discord bot?
help, this was working now it somehow magically isnt ```py
for i in range(0, len(testrange2)):
if testrange2[i].name in teams:
try:
te = testrange2[i]
e = discord.Embed(title='Error', description=f"{member.mention}{member} is already in The {te.mention}{te.name}", color=0xEE1010)
e.set_author(name=ctx.guild.name, icon_url=ctx.guild.icon.url)
e.set_thumbnail(url='https://emojipedia-us.s3.amazonaws.com/source/skype/289/cross-mark_274c.png')
await ctx.respond(embed=e, ephemeral=True)
return
except:
return await ctx.respond('error debug code 7')
Send full code of the command
unknown interaction just means your code somehow took too long to respond
also he's trying to respond with for loop, but he can only respond once, no?
ah nvm hes just trying to find right elem
if it happens very occasionally you might just have a funky internet connection
from discord import Webhook, RequestsWebhookAdapter, message
ImportError: cannot import name 'RequestsWebhookAdapter' from 'discord' (C:\Users\Chain\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_init_.py)
i dont understand the module object is not callable
it's discord.Client()
And you need intents
RequestsWebhookAdapter doesnt work with discord.py 2.0 i think
where
!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.
thank you
In this case you can just do an empty intents but it's a required kwarg
you have a double () inside the client.run
your token isn't define
you must define a string variable named token that has your bot's token
guys i need help, when i run a command i want the bot to DM the output to the person instead of sending the output in the server. the bot is interactive
by saying "the bot is interactive" i mean that every person can use the commands on the bot
user = await client.fetch_user("the user's id")
await user.send("A message")
yeah but the thing is, i wont have the person's ID.
I see, thank you. Also I just removed the token so I didnt show it in the server
or i can think of something better, how can I make the bot interactive only through DMs?
that will be more practical i think
@commands.dm_only()
when i try that, i get this:
bot = commands.Bot(command_prefix='.', intents=discord.Intents.all()) ^^^ SyntaxError: invalid syntax
thats a syntax error
show me how you have it
it must be something like this
bru
its a mess ik
you should pass it under each command that you want it to be only in dms
like this
if i were to put this what do i put instead of "something"
??
yoo @slow fog it works now tysm
welcome
@lyric patio
U didnt do it correct
oh.. how do i do it?
intents = Intents.default()
client = commands.Client(intents=intents)
whats the best option to keep a long list out of the middle of my code? json file?
something i plan to pull things from later with random.choice
storing your list in another file should work fine in any format you want
though if you read from it too often, it might noticeably block your bot's event loop
#Commands
commands = ["delcare","test"]
declare_commands = ["occupy","test"]
content = split(message)
content_word = content[0] #Getting first word
content_prefix = content_word[0] #Getting prefix / very first letter
content_word = content_word[1:] #letters after prefix
content_id = "None."
print(type(content_word))
if content_prefix != prefix: await message.channel.send("{} Prefix not recognised, Use `{}`.".format(message.author.mention,prefix)) #Checking if it is the correct prefix
elif content_word not in commands: await message.channel.send("{} Command not recognised".format(message.author.mention)) #Checking if it is inside commands
else: #prefix recognised & command recognised
I have no clue why but if i put "declare" it says its not recognised?
any ideas on why?
well your list has delcare instead of declare, but are you writing a custom command parser for your discord.py bot?
yea
those declares look the same...
oh
i hate this, ive spent hours and small typo...
are you sure the built in commands extension isnt good enough for your use case?
just cba to use it, rather build my own, not too hard
it does take quite a bit of effort when you start adding more features, but if thats enough for your bot then its fine
i intend in setting it up in a way so its really easy to add to, and it fits the purpose of my bot more
i already have too many hours on this bot due to formating by hand, 1675 lines cuz no other way to do it
well, just make sure you get it right because technical debt's not fun to deal with
oh ik
I dont know how to fix this. im trying to make a command that will send a message with a button
not too worried as it should only be reading from it once a day, just trying to make the main code easier to look at
well it says No module named 'discord_components' which means it isnt installed, your pyproject.toml needs to include it
though discord-components is obsolete given that discord.py and its popular forks already support slash commands and message components
thanks
im back with another question
how do i fix Traceback (most recent call last): File "main.py", line 18, in <module> bot = commands.bot(command_prefix='D!', intents=intents) TypeError: 'module' object is not callable
My code is intents = discord.Intents().all() bot = commands.bot(command_prefix='D!', intents=intents) bot.author_id = 984583981540442124 # Change to your discord id!!! @bot.event async def on_ready(): print('Logged on as {0.user} '.format(bot), end='') print(f'in {len(bot.guilds)} guilds!') print('D!logs') print('None') game = discord.Game("D!help") await bot.change_presence(status=discord.Status.do_not_disturb, activity=game)
It's commands.Bot not commands.bot
Can anyone help we with some slash commands
Tried googling and couldn't find the user slash commands
Like this
that helped, thanks
I want todo the same thing but according to discord The python distributions are Discontinued so there will be no offical python code add slash commands, but there are modules like "Interactions" but if your using replit.com then 9 times out of 10 it wont work, i will keep you posted if i see anything.
I think i found it?
really
discord.Option(
discord.Member,
name="User",
description="Choose",
option_type=2,
)
THANK YOU SO MUCH
Please send an example
Example of an example
bot.command async def hello (ctx):
@brazen stag
wait
what
give me 5min?
async def add(self, ctx,user: discord.Option(
discord.Member,
name="User",
description="Choose",
option_type=2,
), code: discord.Option(int, name="Money", description="Amount")):
if ctx.author.guild_permissions.administrator:
con = sqlite3.connect("./database.db")
cur = con.cursor()
cur.execute("select * from Members where id == ?;", (user.id,))
data = cur.fetchone()
if data == None:
e = discord.Embed(
title = "System",
description="Not in guild",
color=discord.Color.red()
)
return await ctx.respond(embed=e, ephemeral=True)
cur.execute(f"update Member set money = money + {int(code)} where id == ?;", (user.id,))
con.commit()
e = discord.Embed(
title = "System",
description=f"지급성공\n지급자 : {ctx.author.mention}\n지급받은사람 : {user.mention}\n지급금액 : {code}원",
color=discord.Color.green()
)
return await ctx.respond(embed=e, ephemeral=True)```
well, this code is for a game
plz note that
ok
def is_neighbour(Regions,Faction,id):
for Region_selected in Regions:
owner = Region_selected["owner"] #each owned region by occupier
if owner == Faction:
for i in range(len(Region_selected["neighbours"])):
neighbour = Region_selected["neighbours"][i]
if int(id) == int(neighbour):
neighbour = True
print("FOUND")
return neighbour
i cant set owner without it erroring (region looks like this {'id': 104, 'owner': 'None', 'neighbours': [103, 105, 115, 118, 114, 94], 'building': 'None', 'water': True, 'price': 2})
if you want to do a role change discord.Member to discord.Role
okk
Guys why i getting this error again and again
your bot maybe be ip banned, they kill 1 in shell
Why this happened?
Is this replit?
Are you hosting it locally?
On my mobile device
If it's not replit DO NOT kill 1
I not hosting i just running it
Then somewhere in your code you're spamming discord with requests and getting ratelimited
im getting this error Traceback (most recent call last): File "main.py", line 130, in <module> @discord.slash_command(name="Give") AttributeError: module 'discord' has no attribute 'slash_command'
Very big problem for me
I got this error now
okk wait
But i am not spamming anywhere
alright, thank you again
what version are you using
Python 3.8.12
is it pycord?
not sure
well i gave you the pycord code
if you are discord py you will need to use another code
well using a slash command is better on pycord
ok
or do pip install discord-py-slash-command on cmd
idk if that will work
use this also
Guys how can I exit discord bot running i mean how to stop bot running in termux?
Making your bot of in termux?
Traceback (most recent call last): File "main.py", line 17, in <module> from discord_slash import SlashCommand, SlashContext ModuleNotFoundError: No module named 'discord_slash'
Did you do pip install
Yes
Change Give -> give
ok
Hi im using bridge commands with one parameter.
when i use the slash command /command in discord i can see the parameter and discord dont let me submit without providing the value.
But with just prefix command !command i can just submit and in the console i get error discord.ext.commands.errors.MissingRequiredArgument: food is a required argument that is missing.
I understand that it is required to pass !command food but is there any built in validation that pycord provides to handle this instead of catching every missing arguments ?
code:
@bridge.bridge_command()
async def find_nutrition(self, ctx: commands.Context, food: str):
await ctx.respond(f"You searched for {food}")
same error Traceback (most recent call last): File "main.py", line 17, in <module> from discord_slash import SlashCommand, SlashContext ModuleNotFoundError: No module named 'discord_slash'
using pycord?
You could set a default argument for it so it becomes optional, or you could make an error handler
async def find_nutrition(self, ctx: commands.Context, food: str = None):
await ctx.respond(f"You searched for {food}")
i cant, otherwise i will have to rewrite the entire bot to fit pycords standards
ehh dont they have any built in for that ?
no, i mean validation error msg to user when they dont pass argument
i mean i dont want to make 1000 try catch for every commands.
oh wait can i make an error handler at global instead of every command ?
I think that's something like an error handler, but I don't know really much about Pycord
Mhm
nonono
use both
I believe it has an event for it called on_command_error
It'll call this event if an error occurs
Ahhh i see, thanks let me try
ok
ok
Also, they have on_application_command_error for app command error handling
yeah i just found in their docs
question
how, google is giving me nothing. i want to install pycord. i m using replit
ops wrong message
how, google is giving me nothing. i want to install pycord. i m using replit
no
im on a chromebook
How to install Pycord on Replit
(this channel is not by the official Pycord team , i have no relation with the Pycord team.)
.......................................................................................
⏺ \ Recorded with OBS Studio
🎬 \ Made with Filmora X
..........................................................................
im switching to vsc
why pycord :(
So I can get / commands
they not only exist in pycord
discord.py or disnake are just better
discord.py has slash command support
Tell me
tell you
Now
can I stop an on_message_edit? that or make after.content revert back to before.content?
you can do the latter if the message was sent by the bot
Thanks
it would be another user's message. it seems like that's a no go, but I wasn't sure if just stopping an edit was possible
you can't edit messages sent by other users
or stop them
you could delete the message, or use a webhook to "mimic" the old message
The error is literally telling you
Look at Did you mean
What is original_message?
!d discord.Interaction.edit_original_response - There's only edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
type object 'Interaction' has no attribute 'edit_original_message'. Did you mean: 'edit_original_response'?
Hmmm
Did I read anything wrong?
Well uhhh
Look like there's an error in the library
I did misread it 😿
I can't help with that, it's the library's development problem
The last line even suggests what's wrong
pycord moment ;-; ask em to update it
Classic
You should uninstall discord.py and other discord api libraries
my rate is being limited
Ok
It's not like you need the bot code to fix the error
yeah
why are you using that version when 2.1.3 is the latest release
thanks
😂
epik
Pycord is truly something wonderful
and wtf they create a subclass ApplicationContext object using abc. Messageable 🗿
not related to your issue, just kinda triggered me
InteractionContext
anyways do you have a folder called local or bin in the container?
go thru it
find a folder names site-packages
lookup for pycord/ discord
open the file mentioned in the error
and replace the erroring attribute with the correct one
looks like you used the wrong attribute or variable. check the pycord docs
Nice, none of the profile pics are loading
check the lib folder
yes now look into the discord folder
and find your file from which error comes
i also see discord.py there, why?
yes which means the library was installed
consider resetting the python package installations
Go to commands folder
Not ext/commands tho
I meant discord/commands
Go to back to discord
Then go to commands
context.py
Try running your bot again
Just use discord.py 👍
Good idea
would be a good idea tho
what is that import ..., main in your main.py?
wdym core.py
im talking about the import ..., main in your main.py
why are you bringing core.py here
not sure about what?
nor am I
I don't know what is that main, and what do you use it for so nothing I can say
It might be a cause of this error
might not
Let's see what you're doing step by step:
result= all of channels (ids) that have autoreacts- loop through
result(work with eachchannelID) - check if
channelIDis the current channel id:
-- if yes:
--- delete autoreact
-- else (if no):
--- say that there is no autoreact in this channel
Can you find a logic mistake or should I explain it?
no
So you loop through each of autoreact channels.
That means that if there is two or more channels with it then it will get autoreact_channel_id_1
and check if it's your channel id, but your channel is autoreact_channel_3 so it will say that there is no autoreact in this channel, even though there is.
Then it continues the loop, but since you can only respond to an interaction once, when it gets to autoreact_channel_2 it will try to send that there is no autoreact again but will fail.
What you should do instead is check if your channel is in the list of autoreact channels ids, like this if channel.id in [c[0] for c in result]: and then delete the autoreact, or if it is not (else:) then send that there is no autoreact
NOTE: [c[0] for c in result] does the same as for eintrag in result: c = eintrag[0], just puts it in a list
You didn't do what I said
Your code should look like this:
if channel.id in [c[0] for c in result]:
await cursor.execute(...)
await interaction.response.send_message("Deleted!")
else:
await interaction.response.send_message("No autoreact here.")```
you took the note too seriously i guess
It was just an explanation of what [c[0] for c in result] does
channelID = eintrag[0] is odd there
remove
wdym :wtf:
how
what is in your code
audit logs
check audit logs
they usually give clear info about what is happening
in this code there is no deleting messages
okay so its not bulk
then no idea
go ask your friend is he dumb
maybe he is using self-bot
or he is being hacked
or wait
I think you have automod
in your bot
then no idea
this is discord bots tho, not stupid friends
You have a function named set?
it is shadowing
you shouldn't name anything like a builtin name
Not use set as a name for a group
either rename it to something else or maybe to _set
Event
guys how to make requirements.txt
idk if this is the right place but im wanting a pay a python discord bot dev to make me a bot, where is the best place i can find one, fivver is out of the question, too many bad experiences with them
!rule 9
so no ones gonna answer me, huh
Just put the correct name of the package u want, each in separate line and save it as requirements
shouldnt your answer be in the discord.py doc ??
It seems to me that you do. Maybe I did misunderstand something
!d discord.on_guild_emojis_update
discord.on_guild_emojis_update(guild, before, after)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") adds or removes [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").
This requires [`Intents.emojis_and_stickers`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.emojis_and_stickers "discord.Intents.emojis_and_stickers") to be enabled.
like this?
from discord.ext import tasks
import os
from discord.ext import commands
import discord
import asyncio
import re
from datetime import datetime
import aiohttp
import io
import os
import nextcord
import random
mhmm seems like you did, but will leave it at that
discord.py
datetime
os
random
oh alr thanks
sure np
@shell wing
discord.ext
os
discord
asynico
re
datetime
aiohttp
io
nextcord
random
yups
like this?
ERROR: Could not find a version that satisfies the requirement discord.ext
ERROR: No matching distribution found for discord.ext
discord.ext isnt a package from pypi
so how do I write it as?
Let's say we have this:
from aiohttp import ClientSession
from discord.ext import commands
import discord
In requirements.txt it'll look like this
aiohttp
discord.py
Installing discord.py installs aiohttp
It comes with discord.py
The library also installs other libraries
Most likely
(Just for the example 🥺)
Yeah but you don't need the requirement for aiohttp
Unless you need a specific version
some of those imports were useless
so I deleted
Ye, I can't argue with that
how does random sound like?
It's a stdlib
May I ask what's the problem
stdlib?
Oh this
It comes with Python by default, so you don't have to install it
The quickest way is to put in a requirements.txt file the output from running pip freeze
ERROR: Could not find a version that satisfies the requirement stdlib
ERROR: No matching distribution found for stdlib
Unless you have other unnecessary libraries installed on which the project does not depend
You don't
It's a module in the standard library, you don't need to install it externally
just tell me how random sounds like in requirements.txt
You should not list standard library modules in that file
bro without random code doesn't work
just tell me how does random sound in requirements.txt
It seems like you have an error in another area of the project
Or rather I should say a problem
when I remove random it shows error
What error
bro just say how does error sound in requirements bruh
What is your traceback
why wasting time
It doesn't seem possible to me to get an error about a missing standard library module
Have you tried repairing your Python version
..
It's possible if you have the installer
I just need to know how does random sound in requirements..
It sounds like you have a problem elsewhere
What is random sound in requirements
Unresolved reference 'random'
ok happy?
it shows this everywhere when I remove import random
now how does random sound in requirements
You're trying to use random without importing it?
Is random being imported by the file that raises the exception
no this guy was telling me that its part of discord.py so I removed it to show him that he's wrong
Of course
What?
just tell me how does random sound in requirements
tell me how "random" is written in requirements
random is a standard library that comes with Python
Why would you want to add it in there
If the file needs import random, add that line at the top of it
You don't need to list it
Everybody with Python has it
oh alr!
The standard library modules mostly come in tact with every Python version
Maybe they have changes or maybe they don't have support for some platforms
random in python 1.x 🐍🥔
So you never need to list any of them in the requirements file
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
the error..
!paste paste it here and send the link
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.
I am not able to see it clearly right now as it is small and I am under direct sunlight
Is all of it the traceback
its like main.py?
alr lemme change
you asked your host to run bot.py and didn't provide them
ikik
my bad
ok it finally worked
For the protocol, by "the standard library", I referred to the collection of modules that come with standard Python installations (modules like os, sys, time, random). discord.py is not a package/module in the standard library, but a package from Python's package index (PyPi) which you do need to install and should list in a requirements.txt file if you ever need to use such file.
!d discord.on_guild_emojis_update
discord.on_guild_emojis_update(guild, before, after)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") adds or removes [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").
This requires [`Intents.emojis_and_stickers`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.emojis_and_stickers "discord.Intents.emojis_and_stickers") to be enabled.
this event is called when emojis are updated
compare the before and after to find what was added
Hey!
How would would i make it so when i run a slash command i get the options true or false
Like this
Code:
@bot.slash_command(description="Play rps with the bot")
async def rps(ctx, choice:discord.Option(str, "rock, paper, or scissors all lowercase", required=True)):
rpsGame = ['rock', 'paper', 'scissors']
user_choice = choice
comp_choice = random.choice(rpsGame)
if user_choice == "rock":
if comp_choice == "rock":
embed=discord.Embed(description=f"Well, thats weird... We tied??")
embed.add_field(name="Your choice", value=choice, inline=False)
embed.add_field(name="My choice", value=comp_choice, inline=False)
and so on
but i want it so they have a list of options not they type it
@bot.tree.command(name="help", description="Use help to see all of my commands")
async def helpme(interaction: discord.Interaction):
await interaction.response.send_message(f"!mute - Mutes A Member \n !unmute - Unmuted A Member \n !h - Use that command to get help from the staff! \n!say (text) - Says Something", ephemeral=True)```
its not working
!d discord.app_commands.choices
@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.
Example...
@bot.tree.command(name="help", description="Use help to see all of my commands")
async def helpme(interaction: discord.Interaction):
await interaction.response.send_message(f"!mute - Mutes A Member \n !unmute - Unmuted A Member \n !h - Use that command to get help from the staff! \n!say (text) - Says Something", ephemeral=True)```
does anyone know why its not working
pycord
You might just have to wait for it to sync or sync it manually
Try syncing it manually with tree.sync
ill try
It needs to be awaited, and you can also sync it by providing some discord.Object with the guild's ID for it to sync to the guild immediately first
We need more info than "not working" lol
I don't know how slash commands work in pycord
Traceback (most recent call last):
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 50, in <module>
@bot.tree.sync(name="help", description="Use help to see all of my commands")
TypeError: CommandTree.sync() got an unexpected keyword argument 'name
it doesnt shows up
that's not how sync works
You can't sync one command
Where'd u get that from
idk
No, it only takes a discord.Object and syncs all app commands either everywhere (if you didn't pass one) or first to the guild with the discord.Object's ID
thought it was it
What are you trying to do
Why are you converting it to string, then back to a role object with utils.get
Why are you getting the roles again
just keep it as set() - set(), that'll give one Role object
All of the str, join, utils.get is unnecessary
Wait why are u making it a set anyway
to get roles differences
oh yeah i forgot you cant do list - list
property display_avatar```
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
how do I make my Discord Bot work 24/7 (replit / visual studio code, python)
use a vps, not replit.
vps?
You can get guild object with its ID and then access name attribute, just like this
guild = bot.get_guild(id)
name = guild.name```
guys how do i make only certain roles be able to use commands for my discord bot
how to write something in a txt using aiofiles in each line
i just follow this guide right?
Mhm, you can use same logic to implement it on your own roles
Or you can also just check inside the command, if the user has certain role
i am making a bot that you have to purchase to use first, thats why im trying to do this, for now everyone has access and i want only people with the role "buyer" to be able to access the role
or maybe a key system would be more efficent
like you have to redeem a key to be able to use a bot
you should use a database
store the user id, their "plan", and other data you require
im kinda new to this so could you guide me and give me somewhere i can use that database?
If you haven't used SQL or relational databases before, see https://sqlbolt.com
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
im new to making discord bots, i made something but the bot works even without redeeming the key
How do you set a minimum length for a slash command's argument?
For example They have to enter at least 10 characters in order to send the slash command
You can also make the bot check if the user has a role named "buyer"
is this a one-server bot?
if not, you should probably have some sort of file that contains all the buyers user ids
or even better, use the db
oh
and now when i try to run pip this pops up
Fatal error in launcher: Unable to create process using '"C:\Users\Nikola\AppData\Local\Programs\Python\Python310\python.exe" "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\Scripts\pip.exe" list': The system cannot find the file specified.
oh well you can just override the bot's on_message method and return if the author doesn't have the role
try py -m pip list
nice that works now i need to install pymongo and i will see if the code works
it says
Requirement already satisfied: pymongo in c:\users\nikola\appdata\local\programs\python\python310\lib\site-packages (4.2.0)
but it doesnt work when i try to run mongoclient in my program
don't use pymongo though, use motor which is basically the async driver of Pymongo
can i still use mongodb tho?

the command MongoClient still isnt working
absolutely
i dont know what to put here instead
new to python here, how can I make this not case sensitive lol
if message.content == "Hello":
await message.channel.send("Hi")
in nodejs, I'd use ==, if I wanted it to be case sensitive, I'd use ===
not sure how to do this in python though
kategoria4 = await ctx.guild.create_category("━━━━━ GŁOSOWE ━━━━━")
await kategoria4.create_voice_channel("『🔱』ogólny", user_limit = 99)
await kategoria4.create_voice_channel("『🤬』tyralnia", user_limit = 99)
await kategoria4.create_voice_channel("━━━━━━━━━━━━━", user_limit = 99) #how to add conect false?
await kategoria4.create_voice_channel("『🔱』ogólny", user_limit = 99)
await kategoria4.create_voice_channel("『🔱』ogólny", user_limit = 99)```
how to add conect = false?
Just convert message.content to lower case with .lower() and then compare it with your string (which is also lowered)
ty
What do you mean by conect = false?
Make nobody can join the channel?
yes
You can either edit the channel's permission or create the channel with the desired overwrites
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 [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this...
okay
and?
zablokowane = await kategoria5.create_voice_channel("━━━━━━━━━━━━━", user_limit = 99) #how to add conect false?
await zablokowane.set_permissions()```
@tidal hawk will you finish writing today?
I like to write
@slate swan
when i try to run my bot which uses mongoclient i get this error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationFailure: bad auth : Authentication failed., full error: {'ok': 0, 'errmsg': 'bad auth : Authentication failed.', 'code': 8000, 'codeName': 'AtlasError'}
!d discord.Guild.create_voice_channel the overwrites kwarg
await create_voice_channel(name, *, reason=None, category=None, position=..., bitrate=..., user_limit=..., rtc_region=..., video_quality_mode=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This is similar to [`create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`VoiceChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel "discord.VoiceChannel") 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`.
plss help me with this
!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 were trying to send a message with the content as None
Bruh
Content is not a none
I know what is that
I asking how i can fix it
the traceback suggests that your embed didnt have anything inside it
sorry I didn't understand
you'll need to show the code for your help command if you want us to find out why its empty
Intents are required after the 2.0 update
Its very high
I cant send it
can you please give me it in code form I mean what to add there
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.
@naive briar
https://discordpy.readthedocs.io/en/latest/migrating.html#intents-are-now-required
... In order to better educate users on their intents and to also make it more explicit, this parameter is now required to pass in
if you want to know how interactions work in the discord API, you can look into their documentation
https://discord.com/developers/docs/interactions/receiving-and-responding
unless you mean you want to know how a particular library implements them, in which case you'll need to say which library that is
@hushed galleon
You have to pass the discord.Intents to the discord.ext.commands.Bot or discord.Client as kwarg, for example:
bot = discord.Client(intents=discord.Intents.default())
this seems like a rule 5 violation given that discord doesnt allow self botting
Other cmds is working
The problem is in soruce
the API reference sure, but the docs unfortunately dont have their own guide for using interactions/app commands
Traceback (most recent call last):
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/discord/app_commands/commands.py", line 861, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "/storage/emulated/0/Download/ProGamerzbot/cogs/game.py", line 159, in _wild
await inter.response.send_message(file=file,embed=embed1)
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/discord/interactions.py", line 762, in send_message
await adapter.create_interaction_response(
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/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 "/data/data/com.termux/files/usr/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1240, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'wild' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
Guys how can I fix this error?
1 month ago that cmd is worked
Your interaction took too long to respond
If your command takes over 3 seconds to respond, you have to defer it
Hmmm
Can my internet connection be it's cause?
either it's blockingio, latency or you're doing something that needs more than 3 sec to be processed
@hidden hazel you could go through the app commands / message component examples on the github and check out ashley's slash command guide in the second top pin of this channel, you'll find that the process essentially boils down to a user triggering an interaction and your bot answering to the interaction
the github examples: https://github.com/Rapptz/discord.py/tree/master/examples (inside app_commands/ and views/)
How can i make it so commands only work based on a condition e.g. if its a specific channel?
i.e. if i have a command to create a new channel, then in that new channel i want to only be able to execute command x, command x can only be executed in that new channel made no where else
decorator checks
I'm new to python, this doesn't do anything for some reason?
@client.command()
async def ping(ctx):
await ctx.reply(f"Pong! {round(client.latency * 1000)}ms")
command_prefix is set to !
I don't get any errors or anything
Did you enable message_content intent?
intents=discord.Intents.all()
example of decorator check:
def in_channel(channel_id):
def predicate(ctx):
return ctx.channel.id == channel_id
return commands.check(predicate)
@bot.command(name='hi')
@in_channel(568987654567890987)
async def hi(ctx):
await ctx.send(f'hi')
Ahh thank you bro

That helps me im going to try implement it later
is your bot verified?
verified for what?
ok, it is not
I do bots in discord.js lol, I could make a ping command really easily if this was nodejs
I've made multiple commands with the same bot in nodejs
seems like discord.py is just broken though lol
mind showing your full code? also if you have an on_message "event" that might be th issue
Do you have an event named on_message?
yeah, I do, does that mess with it? wtf
Overriding the default provided
on_messageforbids any extra commands from running. To fix this, add abot.process_commands(message)line at the end of youron_message
yes it messes with the commands extension
change .event to .listen()
or what catgal said, works both ways
yeah, it works now, did .listen()
for more info the listen decorator is like Client.on of discord.js it allows you to listen for an event without overriding any internal Client content
How can i bring a variable frm one function into a new function?
!e
def a_function(any_name):
print(any_name)
a_function("a string")
a_function(123)```
@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | a string
002 | 123
Make it global
you're gonna make a lot of people angry saying that 
Jaja
its useful in many cases, except not in a Discord bot
Thank you, how can i do that
!globals
As for discord bots use a "botvar" or a separate module
oop, but this works too
Depends what exactly you want to store in the var and how your code is organised
Why show an example thats would depend on the code's structure and is arbitrary?
i mean that's the most common way to pass variables between functions right?
You never passed a variable kek
That's not really "between"

I was gonna explain what exactly it is but my brain broke
!e
def okay(this):
print(this)
def asdf():
this = "sdafsad"
okay(this)
asdf()```
@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.
sdafsad

@discord.ui.button(label='reload', style=discord.ButtonStyle.green, custom_id='persistent_view:reload')
async def reload(self, interaction: discord.Interaction, button: discord.ui.Button):
urll = https://image.png
embed = discord.Embed(title=f'test ! ', description=f"**[🔗you dont see the link? click me]({urll})**", color=0xff97ff )
embed.set_image(url=urll)
embed.set_footer(text=f"requested by: {interaction.user}")
await interaction.response.edit_message(embed=embed)
@discord.ui.button(label='save', style=discord.ButtonStyle.green, custom_id='persistent_view:save')
async def save(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.user.send (self.embed.image.url)
im trying to send the embed image url in dm but i cant
who can help me please
Ok I figured it out, from 1st formulation the man wanted to bring a var from one function to another but I interpreted it as "make the var able to be used in multiple functions" in fact you can read it without making it global if you define it in outer scope but if you need to write you gotta still make it global
🤓
anyone want to beta test my bot (update), up to 5.5k lines of code now 
What is any_url and where is it defined
I hope they all aren't in one file
any_url is just any url
its for an exemple
no, i got ocd with organizing and
Ok cool
Um, actually, example* 🤓
urll = "https://image.png"
Ok what exactly doesn't work
i cant save the embed image in the first button
and i want when the button "save" is clicked the bot send the embed image in dm (without list.append)
yes i know
Then how are you going to use it
idk
You gotta assign it in reload function ig
bro im just stupid I just had to do self.urll
@discord.ui.button(label='reload', style=discord.ButtonStyle.green, custom_id='persistent_view:reload')
async def reload(self, interaction: discord.Interaction, button: discord.ui.Button):
self.urll = https://image.png
embed = discord.Embed(title=f'test ! ', description=f"**[🔗you dont see the link? click me]({self.urll})**", color=0xff97ff )
embed.set_image(url=self.urll)
embed.set_footer(text=f"requested by: {interaction.user}")
await interaction.response.edit_message(embed=embed)
@discord.ui.button(label='save', style=discord.ButtonStyle.green, custom_id='persistent_view:save')
async def save(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.user.send (self.urll)
like this
how do I make an argument in a command not required?
give it a default value
I did lol
Show the function
@client.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member:discord.Member, *, reason:None):
if reason == None:
reason = 'because fuck you, thats why'
await ctx.guild.kick(member)
await ctx.send(f"User {member.mention} has been kicked for {reason}")
I did reason=None, that did the trick I guess lol
Yup
I'm new to python, what difference does it make
That annotation isnt correct, you need to specify the default's type
Why the check? just use the string as the default value
you can provide reason while kicking someone
!d discord.Guild.kick
await kick(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Kicks a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have [`kick_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.kick_members "discord.Permissions.kick_members") to do this.
Whoah since when does discord display discord and server join date :3
A while ago. They changed it like 3 times now because discords UI department is utter dogshit
I'm not on a beta version of Discord so I just know now.
I don't want frequent updates.
can you get a file as an argument in slash command?
Yes, it's discord.Attachment
for disnake?
Ye
hey how can i use a webhook to upload files into a discord channel?
Anyone bored and wanna test my game bot? 1 gold star to anyone who finds a bug 
sure?
What's gold star 🤨
Can i post links here or do i need to DM not to annoy mods
just dm the link to me
sent the link
it's a magical imaginary prize that you can flaunt over other people
Hey i have a problem
I have installed discord components and I don't know what's happened
Or there is something else to install
anyone else up for beta testing for my discord game bot? last time i ask 
I would like if I had time 😢
i did a google and invalidargument was removed from discord.py
hello.
more info here for ya
I even have a hanging project, I haven't made changes in it for like half a year
well just a little bit
can you make a slash command accessible to only a specific user?
I feel like when I'm gonna get to continue it's development, discord will already make bots completely useless
wait what
yes that's new
You can grey out the slash command for specific permissions but not user?
and you can also make a slash command accessible to only one user
well it will show up for everyone, but will be accessible only for that person
as an owner?
but not for certain people
why not?
def prefix_exciting_bruhness(client, message):
p = await db.get("SELECT prefix FROM prefixes WHERE u_id = %s", (message.author.id,))
return p
bot = commands.Bot(command_prefix=prefix_exciting_bruhness)```
ikr my profile is a big flex now
?
big flex
I wouldnt call wasting your time on discord a flex
no offense to the user of course
If you were to make snake on discord, how would you think of it to go? How would oyu make it\
How to get that
open someone's profile
Bro check your pings, mobile client doesnt have it yet
?
how can i make the user a variable?
Still not there
update discord
I'm pretty sure mobile client doesnt have it yet
oh
I can say it as my mobile client is up to date and i dont have it
That's how discord does it, give new features to the desktop client and after a few weeks or months they give it to mobile clinet
i am coding on vsc and im getting this error /bin/python3 "/home/danielchudnovsky154/Shape of an L on the forehead/main.py" Traceback (most recent call last): File "/home/danielchudnovsky154/Shape of an L on the forehead/main.py", line 13, in <module> from discord_slash import SlashCommand, SlashContext ModuleNotFoundError: No module named 'discord_slash' and i used pip install -U disscord-py-slash-command help
Looks like you've got an extra s
where
Either way discord.py has native slash commands built in, why do you need discord-py-slash-command anyway?
From what I'm hearing the library isn't all that good
the only way i knoe
where
Well the documentation is pretty clear
Has all of the interactions related stuff
Aka he followed a discord tutorial on youtube.
unfortunately way too common
@sick birch i changed from discord_slash to from discord
the best we can do is spread awareness to just stick with the implementation your fork of choice provides
The github repo has excellent examples on using slash commands, i suggest you start there
ok
Excellent is the last word i would call them, you only said that because you made them kek
CAN ANYONEEEEEEEEEE HELP MEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
self.bot
Sure, what's the issue?
Didn’t work
I’ve tried all of it lmao
Seems like a lib issue
Hello, good afternoon person. Has anyone used selenium? I'm not sure how can I leave more than one chrome running together
with ur own you mean one from github right?
no i bought it
the guy I bought from refuses to help me
it's discord.Bot
Thats sucks
oh one sec
Maybe also check the file for malicious code I seen a few ppl sell boost bots with malicious code in them
yeah i checked there isnt
If you couldnt troubleshoot a TypeError how could've you detected malicious code, no offense?
A person i know went through it
I am getting this error
Those bots are against ToS
