subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, ...)```
Run the command described by *args*. Wait for command to complete, then return a [`CompletedProcess`](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess "subprocess.CompletedProcess") instance.
The arguments shown above are merely the most common ones, described below in [Frequently Used Arguments](https://docs.python.org/3/library/subprocess.html#frequently-used-arguments) (hence the use of keyword-only notation in the abbreviated signature). The full function signature is largely the same as that of the [`Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen "subprocess.Popen") constructor - most of the arguments to this function are passed through to that interface. (*timeout*, *input*, *check*, and *capture\_output* are not.)
#discord-bots
1 messages · Page 967 of 1
You'd make this run all of your files manually
how would i do it with 3 different bots?
Three calls of this ^ each running their respective file
If you happen to take a look at the documentation I sent, they show a few examples
!paste
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.
what do i need to import to make this work?
It's an interface for your shell, so you enter the command in which you would run your python file
i don't have access to a shell in heroku it uses workers
class subprocess.Popen(args, bufsize=- 1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, ...)```
Execute a child program in a new process. On POSIX, the class uses [`os.execvpe()`](https://docs.python.org/3/library/os.html#os.execvpe "os.execvpe")-like behavior to execute the child program. On Windows, the class uses the Windows `CreateProcess()` function. The arguments to [`Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen "subprocess.Popen") are as follows.
*args* should be a sequence of program arguments or else a single string or [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object). By default, the program to execute is the first item in *args* if *args* is a sequence. If *args* is a string, the interpretation is platform-dependent and described below. See the *shell* and *executable* arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass *args* as a sequence.
Can someone help me with my reload command cog thingy pls
I barely use this library ¯_(ツ)_/¯
whenever I try to reload, I get this error
https://caught-lackin-in-8k-by-cyberghost.cf/XQBztjrq
Here is the code:
https://paste.pythondiscord.com/eviyuvojov
only thing i hate about discord, you cant edit owner's nicks TY THO
That code isn't what we want
so where exactly am I implementing it im confused?
We want your ping extension code
I sent as a paste
Why are you giving us the owner code
Yeah well he looks like he's not getting it from what you're saying
Better to ducking point out where and what to change in the code
That's what i learned mostly from people
have you used this before? the docs doesn't make much sense
Member is none
o
Got it working thanks!
You should be passing the ID of the user, not the name + discrim
The error seems to say you passed a string instead of an Int
do you know what a procfile is?
NVM my command that inserts the id to the database used to be name i forgot to change it to ID
now it works
no errors
yes
oh any idea why is get faster?
this is usually something you dont need to write since all guilds are cached when the guilds intent is enabled; afaik from 0_0's context they likely have it enabled but they're running their code in a task loop, so to handle uncached guilds you'd have a @before_loop to wait until the bot is ready
so what would get return if it had failed
Replited?
Well it is what heroku uses for processes
I wasn't actually gonna say anything because i thought it was something about replit
But looked weird to me so
Specifically using Bot.wait_until_ready(), this can either be in the before_loop or directly in the task loop
Either way there is no harm done, it would only make an API call when not cached
this?
This would just be an additional sanity check
i would say to only write it when it is necessary, e.g. when you're sharding your bot and you have functionality that may require accessing guilds that are outside the shard making the request (note: i have not done sharding before so this is only theoretical, maybe im wrong)
So from my understanding icon_url=ctx.author.avatar_url puts the person who does the command's avatar in the footer however it says Member not defined when I try to execute this. Do I need to store the member's id and then call something to get their avatar?
Heres my code so far
@commands.command()
async def ping(self, ctx):
before = time.monotonic()
ping = (time.monotonic() - before) * 1000
embed = discord.Embed(color=0xff0000)
embed.add_field(name="Bot Latency" ,value=f"API latency: **{int(ping)}ms**", inline=False)
embed.set_footer(text="Requested by: {}".format(ctx.author.display_name, icon_url=ctx.author.avatar_url))
await ctx.send(embed=embed)
and it spits this error
AttributeError: 'Member' object has no attribute 'avatar_url'
in their use case which is having the guild to do a fetch_member then its alright, but fetch_guild omits information like channels so it might not always be sufficient
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
it got changed in 2.0
No wonder its been doing my head in this entire time
thanks
so would it be icon_url=ctx.author.avatar?
avatar.url yea
Yep, but channel data should almost always be given. If not from the RESTful request, you'd get it from the gateway
Ah thanks
And if they have access to the guild anyways, I'm gonna assume logically it's already cached internally
Since when your bot connects to the gateway you receive X GUILD_CREATE messages which have the channel data
And with the way discord.py handles it, you won't receive on_ready until all Futures have finished, and the futures would be corresponding to the guild for caching
yeah those are true by themselves, but im just talking about fetch_guild
Even after the using
icon_url=ctx.author.avatar.url
it wont display my avatar?
https://caught-lackin-in-8k-by-cyberghost.cf/ub7sQTae
Yep agreed, but my point being, if you have access to the guild, E.g allowing for fetch_guild that would already mean your bot can see it from the gateway
Meaning fetching it would kind of be not required
If that doesn't work out, which I highly doubt; this endpoint exists GET /guilds/{guild.id}/channels
Meaning, if you only fetch the guild for channels, that would be useless, instead use the above ^
Getting rid of the whole case where channels would somehow be omitted
wouldnt it be 100% required during initial iteration if the wait_for_ready was missing?
Not 100% but you'd have a race condition
It wouldn't make sense not to wait until it's ready anyways
yeah, but i replied to your earlier comment mentioning that it would be no harm done making an API call when not cached, so i assumed you meant the case where they didnt wait until ready
What about you try just .avatar🗿
Sure, but it's also nice to have in case of any hiccups with the REST api
As they documented on the offical docs, it can be None
I cannot, un-suprisingly, read the source code of the API
So I can't say 100% sure what cases where channels is None
It's better to have a second call to fallback on that does no harm in this case
It's not costing you anything either way, and the ratelimits aren't that small
wait what can be none
channels
for the fetch_guild endpoint?
Fetching the guild from the REST Api returns a Guild object, the documentation for the Guild object shows channels?
Meaning channels can be omitted in cases
i have a question i am going on a trip and want heroku to cover for me is there a way that heroku can run 3 bots at the same time?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'avatar'
avatar.url leaves no errors but it doesnt work also
Matter of fact, there is no exposed ratelimit
The only thing that would be "negative" is the bandwith usage
Even then it's neglible as this is your fallback
How can i add cooldown?
oh yeah i guess they didnt document the cases where it could be missing, though the example for the GET guild endpoint does show the channels key to be omitted
If that ever happens you can just use GET /guilds/{guild.id}/channels
i still think the cost is code readability/redundancy, cause getching the guild would imply the case where you only have partial data
It would be redudant if we knew in what cases channels would be empty, or None. But we dont' so this is just a fallback call in case it DOES happen. And it doesn't affect too much on the readability part either? Not to me at least; hell if want to make it even more readable just make it in a ternary condition
How can i show cooldown to user? As How much time left.
i dont know much about heroku but i think it would be possible, either by running multiple processes or writing a single script that starts each bot in the same event loop
In {}
is this for handling a CommandOnCooldown exception?
Yes
!d discord.ext.commands.CommandOnCooldown.retry_after
The amount of seconds to wait before you can retry again.
Ty
note that the other attribute .type is specific to dpy 2.0, in dpy 1.7 its stored within the .cooldown attribute
in case you were planning to use that too
well i can start that script i just have no idea on how to write a script
Okayy
I meant ctx.author.avatar not ctx.avatar tf 🗿
any ideas on how?
oh wait it is documented, the * next to channels? * is referring to the footnote that its only supplied in the GUILD_CREATE event, so with the assumption being that the cache is only populated by the gateway and not the API, get_guild should be guaranteed to have channel data
even then it throws it
@client.command()
async def say(ctx, *, text):
if ctx.author.id not in [123, 456, 789]:
return
message = ctx.message
await message.delete()
await ctx.send(f"{text}")```
how do u make it so u specify a channel, like -say [#discord-bots](/guild/267624335836053506/channel/343944376055103488/) hi
Ah, ok I missed that part. Falling back onto my point though, this isn't costing you much right? So there isn't a reason really not do it. And either way their usecase wasn't even utilising the call for channel data
?
hello anyone there?
i need help
@blissful sparrow what error
are you on vsc again
you can use a main, async function and asyncio.gather() to start multiple bots at the same time, e.g. ```py
async def main():
party_bot = MyPartyBot()
war_bot = MyWarBot()
await asyncio.gather(
party_bot.start(<token>),
war_bot.start(<token>)
)
to run the main function:
asyncio.run(main())```
yeh but it actually works now
try on thonny again
add a parameter just before the * and typehint it with discord.TextChannel to have the first word you write be converted to the channel
can u help me with that
those two bot files can be next to your main file and then imported
there is 3
main beta_bot and bot
as in you also have a third bot coded in the main file?
how does that have to do with discord bots?
SQLite Database
This wouldn't work, not as intended that is. since you await asyncio.gather with how start works, the first start will be blocking the second start call. You should be doing ```py
loop.create_task(party_bot.start(...))
await bot.start(...)
I want to make a ticket bot
no i have master for the process and 3 different bots all in different files
ah thanks, i thought from the docs they meant gather would actually schedule them as tasks before waiting on the first one
Well it kind of does
The thing is though, your awaiting it
As I mentioned in my message
you don't need a database browser
Why?
also, you should be asking that in #databases
cause you don't need one?
its useful but not needed
wym, doesnt it only schedule the first one regardless of whether its awaited?
It does it concurrently
All of them
ah oops i used a blocking while true in my testing
So I can make a ticket bot without database?
And everything will work?
yes
Internally start has a few while Trues as well
ticket bot has nothing really to do with a database, and even if you use one
you dont really need a database browser
exactly
Ic
especially in the case of sqlite3
Thanks
in message purge error
hm, i tested both gather and create_task and the two bots still connected serially, although maybe this is just cause i tested with a single token instead of two py async with bot_1, bot_2: await asyncio.gather(bot_1.start(token), bot_2.start(token)) # vs. asyncio.create_task(bot_1.start(token)) await bot_2.start(token) INFO in discord.gateway: Shard ID None has connected to Gateway: ... connected ready INFO in discord.gateway: Shard ID None session has been invalidated. INFO in discord.client: Got a request to IDENTIFY the websocket. disconnected ... INFO in discord.gateway: Shard ID None has connected to Gateway: ... connected ready
code?
in that middle part of the error it shows you tried to format the description using {ctx.author.mention} which wasn't provided by your format() call
Which print belongs to the bottom and which belong to the top?
i uh, cheaped out by using the same function for both bots
you need to pass the mention as well, e.g. ```py
mention = 'Alice'
retry_after = 10.3
'{} needs to wait for {} seconds'.format(mention, retry_after)
Alice needs to wait for 10.3 seconds
or with named placeholders:
'{who} needs to wait for {n} seconds'.format(who=mention, n=retry_after)```
wtf 1 connected 1 ready 2 disconnected 2 connected 2 ready
A sec
@sil.error
async def sil_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
embed = discord.Embed(
title=":clock1: Sakinleş",
description = "{ctx.author.mention}, bu komutu **{zmn}** saniye sonra tekrar kullanabilirsin".format(error.retry_after)
)
await ctx.send(embed=embed, delete_after = error.retry_after)
from __future__ import annotations
import asyncio
import os
import discord
class First(discord.Client):
async def on_connect(self) -> None:
print(f"{self!r}")
class Second(discord.Client):
async def on_connect(self) -> None:
print(f"{self!r}")
async def main() -> None:
TOKEN = os.environ["DISCORD_TOKEN"]
first, second = First(), Second()
await asyncio.gather(first.start(TOKEN), second.start(TOKEN))
asyncio.run(main())
╭─ andy@arch ~/Development/test
╰─$ poetry run python test.py
<__main__.Second object at 0x7fd7b0bbb3d0>
<__main__.First object at 0x7fd7af6f8940>
```It doesn't block
This is really confusing me, shouldn't it be blocking the second call? It's being await'd
from __future__ import annotations
import asyncio
import os
import discord
class First(discord.Client):
async def on_connect(self) -> None:
print(f"{self!r}")
class Second(discord.Client):
async def on_connect(self) -> None:
print(f"{self!r}")
async def main() -> None:
TOKEN = os.environ["DISCORD_TOKEN"]
first, second = First(), Second()
await first.start(TOKEN)
await second.start(TOKEN)
asyncio.run(main())
``` this blocks the second call from ever happening
@devout iris see this message i sent
Ah sorry, tysm
And looking at the source code, gather will be returning a _GatheringFuture which is a subclass of Future, therefor the await should still be working the same. Making the code wait for the Future to have a result
gather schedules all coros as tasks before awaiting right, and .start() definitely cant block the event loop, otherwise it wouldnt be running, so the two starts are able to share the event loop
while in the latter example the second start is held up by the first start being awaited
But if you await a task it will wait for it to have a result
well there's three different tasks running with gather right
two tasks are handling their bots while the main task is just awaiting on those two tasks, so main has no effect on them
also i double checked with a message event to make sure they really were running and the on message event did fire for both of them, 10ms apart INFO 2022-04-09 22:40:36,306: 1 received message INFO 2022-04-09 22:40:36,316: 2 received message
whats the annotations for?
it makes all annotations into strings
why the hell would you want that
Backwards compatability
i.e usage of pipes
I want to typehint with stuff from 3.10+ without making people using 3.10> to suffer
pipes?
doesn't look like one
!e ```py
from future import annotations
import inspect
def foo(bar: str) -> None: ...
print(type(inspect.signature(foo).parameters.get("bar").annotation))
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
<class 'str'>
!e ```py
import inspect
def foo(bar: str) -> None: ...
print(type(inspect.signature(foo).parameters.get("bar").annotation))
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
<class 'type'>
what does it look like then a home?
bro
your bot was not invited with application commands scope in that server
https://discord.com/api/oauth2/authorize?client_id={YOUR_ID}&scope=applications.commands
My acc id?
your bot's ID
Ok
snowflake basically means ids
@app_commands.guilds(957886366589542450)
async def my_embed(ctx):
embed = discord.Embed(title="Quote 3: ", description=f"An experimental discord.py file that you can use to improve on your coding knowledge, Ill try my best to give you what you are asking for. (`Create a ticket for more info on this quote`)", colour = discord.Colour.blue())
button = Button(label="Click to create a ticket!", style=discord.ButtonStyle.secondary)
async def button_callback(interaction):
conn = db.connect("dpyhelp.db")
cur = conn.cursor()
cur.execute(f"SELECT Open FROM Ticket WHERE User_ID = {interaction.user.id}")
req = cur.fetchone()
if req == None:
guild = ctx.guild
category = discord.utils.get(ctx.guild.categories, name="Tickets")
channel = await guild.create_text_channel(f"Ticket-{interaction.user}", category=category)
await channel.set_permissions(interaction.user, read_messages=True, send_messages=True, read_message_history=True)
await channel.edit(permissions_synced=True)
sqlite = (f"INSERT INTO Ticket(Open, User_ID, Channel_ID) VALUES(?,?,?)")
vals = ("Y", interaction.user.id, channel.id)
cur.execute(sqlite, vals)
conn.commit()
await interaction.response.send_message("Ticket created! Look at the ticket category to check for your ticket.", ephemeral=True)
embed = discord.Embed(title=f"Press the close button to close this ticket!", colour = discord.Colour.blue())
button2 = Button(label="Close the ticket!", style=discord.ButtonStyle.secondary)
async def button2_callback(interaction):
await interaction.channel.delete()
cur.execute(f"DELETE FROM Ticket WHERE Channel_ID = {channel.id}")
conn.commit()
conn.close()
await ctx.message.delete()
view = View()
view.add_item(button)
await ctx.send(embed=embed, view = view)```
How can I add slash commands?
I tried but didn't work
Did you sync?
may i know what does not work?
like does the slash command not get created? or you get some errors
another sidenote, use async bridge for sqlite
!pip aiosqlite
anyone got an snippet of a command to change the status of the bot?
!d discord.Client.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter...
the Example below
if you want a permanent presence, best way to do it is inside the Bot/Client class itself
bot = commands.Bot(..., status=discord.Status.idle, activity = discord.Game("..."))```
client does not have a process_commands , its a method of Bot
!d discord.ext.commands.Bot.process_commands
await process_commands(message, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
Changed in version 2.0: `message` parameter is now positional-only.
@slate swan this is the line I have, and it is breaking my code:
await client.process_commands(message)
I am trying to fix it
Why not use bot as var?
I find client better
It's a matter of preference at that point
No
I come because I have an error that has never popped up for me until today
Whats the error?
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 415, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Student\Desktop\Lofi-Chill Rewrite\main.py", line 153, in on_message
await client.process_commands(message)
File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 1091, in process_commands
ctx = await self.get_context(message)
File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 1001, in get_context
prefix = await self.get_prefix(message)
File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 946, in get_prefix
ret = await nextcord.utils.maybe_coroutine(prefix, self, message)
File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\utils.py", line 512, in maybe_coroutine
value = f(*args, **kwargs)
File "c:\Users\Student\Desktop\Lofi-Chill Rewrite\main.py", line 26, in get_prefix
prefixes = json.load(f)
File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
how do I make arguments optional?
!d typing.Optional
typing.Optional```
Optional type.
`Optional[X]` is equivalent to `X | None` (or `Union[X, None]`).
Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the `Optional` qualifier on its type annotation just because it is optional. For example:
```py
def foo(arg: int = 0) -> None:
...
``` On the other hand, if an explicit value of `None` is allowed, the use of `Optional` is appropriate, whether the argument is optional or not. For example...
Or default value
Either this or async def foo(ctx, member = None)
nember lol
👀
!json
When using JSON, you might run into the following error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
This error could have appeared because you just created the JSON file and there is nothing in it at the moment.
Whilst having empty data is no problem, the file itself may never be completely empty.
You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.
Different data types are also supported. If you wish to read more on these, please refer to this article.
!json
When using JSON, you might run into the following error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
This error could have appeared because you just created the JSON file and there is nothing in it at the moment.
Whilst having empty data is no problem, the file itself may never be completely empty.
You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.
Different data types are also supported. If you wish to read more on these, please refer to this article.
!json class{
and the code?
I fixed it
just change .event to .listen()
But
ah alright
I have a new error
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 415, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Student\Desktop\Lofi-Chill Rewrite\main.py", line 153, in on_message
await client.process_commands(message)
File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 1091, in process_commands
ctx = await self.get_context(message)
File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 1001, in get_context
prefix = await self.get_prefix(message)
File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 946, in get_prefix
ret = await nextcord.utils.maybe_coroutine(prefix, self, message)
File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\utils.py", line 512, in maybe_coroutine
value = f(*args, **kwargs)
File "c:\Users\Student\Desktop\Lofi-Chill Rewrite\main.py", line 28, in get_prefix
return prefixes[str(message.guild.id)]
KeyError: '962476725839745045'
🤔
@slate swan
This is the error
But idk what it means ig the line works without it
What I meant was the line usually works
the server is not in the json
are you using on_guild_join to add the servers to json?
await guild.create_text_channel()
Is this how to create a channel?
I want to make a ticket bot and I want tickets to be with numbers
For instance: ticket - 1 or ticket - 991
can you define more behavior around that?
Do I need database for that
most likely
discord.ext.commands.errors.MemberNotFound: Member
keep getting this error even i am passing right argument
Show code
async def check(ctx, member : discord.Member):
if member.id == 945984774760194149:
await ctx.send(member.name)
else:
await ctx.send("false")```
How are you invoking the command?
like this !check 945984774760194149
Give the full error traceback
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 552, in transform
return await self.do_conversion(ctx, converter, argument, param)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 505, in do_conversion
return await self._actual_conversion(ctx, converter, argument, param)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 451, in _actual_conversion
ret = await instance.convert(ctx, argument)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\converter.py", line 187, in convert
raise MemberNotFound(argument)
discord.ext.commands.errors.MemberNotFound: Member "945984774760194149" not found.```
typehinting an argument to discord.Member allows you to mention them while invoking your command
for example
!check @slate swan
Doesn't have to be a mention
it gives same error i already tried
discord.ext.commands.errors.MemberNotFound: Member "@Sharp#6991" not found.
Is that your id? @slate swan
nope
what version of dpy are you using
if you are not sure print discord.__version__
Show code
Nvmd got it
1.7.3
then i think the error is it isnt a valid member
Show how u did the command
double check to see if the id actually exist
and is a guild member of the guild where you invoked the command
maybe you also need the member intent
you sure?
nah
it can be a id
bad
it wouldnt really matter as dpy parses the mention
!check 945984774760194149
i usually typehint with typing.Union[discord.Member, discord.User]
It depends on the command purpose
it really depends
nah its vaild member okey wait i am trying using my own id
the problem?
do you enabled the guild member intent
and that member is in the guild you invoked the command
it couldnt find the member its really that easy
note: you also need to enable the intent in both the dev portal and code
its not a valid id
Ping the member
With this command
!check @nimble plume
they get the same error
@slate swan
he said its himself
discord.ext.commands.errors.MemberNotFound: Member "@Dyno" not found.
have you enabled the guild member intent? is hat member in the guild you invoked the command? you need to enable the intent in both the dev portal and code.
do you have intents?
^
its on from portal
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
it has to be done in code too
intents.members = True
intents.presences = True
intents.messages = True
client = commands.Bot(command_prefix="!", intents=intents)```
is it in dev portal as well
and are you invoking the command in a dm or a guild?
surely it can't be...
is it something with guilds intent or is it just me
yes it is
maybe sometimes people do it😳
guild
something is off for sure
how are you invoking the command?
!check 944853480584146944
have you tried mentioning yourself?
Bruh?
@slate swan ?
Listen
ok?
nah guild intents is for stuff related to guilds i.e on_guild_join
Firstly
!d discord.on_guild_join
@client.command()
async def check(ctx, *, member : discord.Member):
if member.id == 945984774760194149:
await ctx.send(member.name)
else:
await ctx.send("false")
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
making it a kwarg wont make a difference
ye
how did it become a kwarg?
He just did !check @nimble plume in his server
it won't work
how do you know this?
- in params means all arguments after are kwarg while / means all arguments before are positional only
See the error
forget this but
!check 944853480584146944
you're not the only one with the first name Dyno
dude, you should start re-writing dpy
this screams bad invocation
do this
Bruhhh
!check 884024529914069003
@slate swan
!check 944853480584146944
this is bot id and currently in my guild
check it and see
i tried everything i get same error
Show
discord.ext.commands.errors.MemberNotFound: Member "884024529914069003" not found.
it is
^?
this whole convo is making me laugh
Bro
it's a correct ID, it's returning None from the converter
why dont you tell the solution

it's not even funny?
Intents!!
he said he did that already
Impossible
yeah its just funny how you guys cant follow a simple tb😭
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.
full code
from discord.ext import commands
intents = discord.Intents()
intents.members = True
intents.presences = True
intents.messages = True
client = commands.Bot(command_prefix="!", intents=intents)
@client.event
async def on_ready():
print("bot is running!")
@client.command()
async def check(ctx, member : discord.Member):
if member == 884024529914069003:
await ctx.send(member.name)
else:
await ctx.send("false")```
do you know what typehinting Member does?
the id statement will always be false lol
you're comparing an object to an int
Intents!! @nimble plume
if member.id ==
^
also do this
useless else btw
wdym
including you
no?
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
I do
what does it do
😳
import sys
import traceback
@client.command()
async def check(ctx, member : discord.Member):
if member.id == 884024529914069003:
await ctx.send(member.name)
else:
await ctx.send("false")
@check.error
async def check_error(ctx, error):
if isinstance(error, commands.MemberNotFound):
await ctx.send("member not found")
else:
print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
@slate swan can you do this and send a screenshot of when you invoke the command and what the bot does?
why????
ok
in the error it already raised a member not found???
and its member not memer😭
Memer
cant find the meme
are people here too interested in memes or something
😳
yes
ok
@spring flax
code
async def check(ctx, member : discord.Member):
if member.id == 884024529914069003:
await ctx.send(member.name)
else:
await ctx.send("false")
@check.error
async def check_error(ctx, error):
if isinstance(error, commands.MemberNotFound):
await ctx.send("member not found")
else:
print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
error - member not found
useless attempt
yea
what are you even trying to do 🏃♂️
hes just catching an error and print the simplified version of it😭
just print the error instead of raising it
nah, just pass it
just dont handle it at all
just let it be raised lol
@bot.listen()
async def on_command_error(context, exception_):
... ``` :chad:
let the users assume what went wrong themself
very pog
PoV: Discord API is acting up
when is it not
Koala, try except doesn't work in on_command_error
@vital crest
he means in a command which is very inefficient
Yup
bro you changed your pfp and pinged someone with the same pfp💀
never seen someone change their identity so fast
funny

Hi im new
the heck
My windows fcked up
same code is running on linux without errors
this guy has like 3 identities
thats weird
Hi bro
not related for this channel
anyone who is having actual off topic conversations not related to this channel or it's purpose, go to one of the off topic channels to not well, clutter up this channel far more than it already has been.
@slate swan@slate swan@spring flaxthank you guys my error is solved
just by including intents.guilds = True
<@&831776746206265384> help?

ok,sorry
thats what I actually suggested 😔 but okimii turned me down on that one
@true wharf dont spam gifs, and keep things appropriate
hello
you are gem dude
anyways thanks
it doesnt need it!
no it works with guild intents
hola, Mina
good for you, but it doesnt need it at all!
afaik
let me check dev portal
only if you didnt played with the Intent class
which he didnt
intents = discord.Intents()
intents.members = True
intents.presences = True
intents.messages = True```
definately did
yeah i did
intents.members = True
intents.presences = True
intents.messages = True
intents.guilds = True```
i thought you ment subclassing it😡
discord.Intents.default()
@slate swan And its recommended to switch to dpy 2 already
just change it to ```py
intents = discord.Intents.default()
intents.members = True
intents.presences = True
intents.messages = True``` and you're fine
cause there still are many intents you miss
why not just use all()?
^^
cause message_content is an intent too
messages?
and its different from Intent.messages
huh
elaborate?
!d discord.Intents.messages
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.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
• The message was sent by the client
• The message was sent in direct messages
• The message mentions the client
This applies to the following events...
but stil why default? because it sets guild as well?
but im confused on why it would use the guild intent
there's no role for that in this issue, but it's helpful since without the default intents methods like get_role/get_channel etc wont work
and it doesnt hurt to have them since they dont need to any verification
idk either
im still confused on how this error was raised maybe an invocation error?
they have a member argument, and the bot was unable to get/fetch that member ez
@client.command()
async def check(ctx, member : discord.Member)```
does dpy parse the mention/get the id and then it would fetch or get info then create the obj?
discord/ext/commands/converter.py lines 192 to 194
.. versionchanged:: 1.5.1
This converter now lazily fetches members from the gateway and HTTP APIs,
optionally caching the result if :attr:`.MemberCacheFlags.joined` is enabled.```
you could say that
@bot.event
async def on_voice_state_update(member, before, after):
if before.channel is None and after.channel is not None:
print("difference")```
this event is working for all guild the bot is in how it will be set for different guilds
i would check deeply into src but im on mobile and its late lol
anyone know?
member.guild gets the guild object where the change took place
!d discord.Member.guild
The guild that the member belongs to.
but i use get_channel and it works fine. no intents enabled anywhere
because if you dont change it, its discord.Intents.default()
i dont have that either
How can I store more than 1 thing in a json file. e.g channel_id: id, id
for subclassing bot, to make a custom function is @property better or making a function?
what's wrong? ```py
def init(self, **kwargs):
super().init(**kwargs)
self.start_time = datetime.datetime.utcnow()
def bot_uptime(self):
#return datetime.datetime.utcnow() - self.start_time
delta_uptime = datetime.utcnow() - bot.launch_time
hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600)
minutes, seconds = divmod(remainder, 60)
days, hours = divmod(hours, 24)
#return days, hours, minutes, seconds
return (f"{days}d, {hours}h, {minutes}m, {seconds}s")
@bot.command()
async def uptime(ctx):
await ctx.send(bot.bot_uptime)
The command output is `<bound method Bot.bot_uptime of <main.Bot object at 0x00000266AA445D50>>`
Isn't bot_uptime a method
You don't need to have it , discord.Client sets that by itself.
Use @property decorator on that method to make it a property
Okay but what's wrong rn?
Nothing's wrong , you either need to call that method, or make it a property
user_id = interaction.author.id
Ah
Interaction has no tribute to author
interaction.user
Normally I used ctx but I switched to slash commands
!d discord.Interaction.user
The user or member that sent the interaction.
Ty
What does this mean
why does this happen in replit when installing a module in the packages
That doesn't even show the full error...
Can I press button and get the selected drop down value? How
What does this error mean
we cant even see the full error bruh
Howdy, after creating my bot I decided to use Cogs to make it cleaner and easier to read. Now, I have a command that only certain role can use, but I don't really know how to make it. I have a json file containing the roles id allowed to use that command, but I don't know to implement it. I know there is @commands.has_permissions(administrator=True) but how can I do the same for the roles id in that file?
?
.. u realise u couldve expanded the error tab or copy pasted the error
Oh.
anyways, res has no items
Ok
I've tried this
!d discord.ext.commands.has_any_role
@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.
Similar to [`has_role()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.
This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
if id_user in dic.keys() or ctx.message.author.server_permissions.administrator:```
but I have this error `Command raised an exception: AttributeError: 'Member' object has no attribute 'server_permissions'`
its probably guild_permissions
@commands.has_any_role(role_id1, role_id2, ...)```
server is generally not used, its guild
That's not the full error, it literally explains nothing.
The screenshot is hiding half part of the error
and I can make a self.id = load(open(rolesid), 'r')!
..
u can use ctx.author tho
@commands.has_any_role(role_id1, role_id2, ...) seems to be a better options
and also that
yeah?
sparky.....its the same thing, just that it reduces bad code practices
Yeah because i'm using classes, so a self.idroles seems to be a great option to use the command you suggested
thansk ashley !
How can I fix it
You can't access self in a deco tho
in a what?
🐢 why do you want it to be a class variable and not a normal global one
@bot.command()
async def test(ctx: commands.Context):
roles = [role.id for id in ctx.author.roles]
if 12245594949 not in roles: return
@bot.command()
@commands.has_any_role()
async def test(ctx: commands.Context): ...```
now tell me which one seems better huh?
2 ofc
idk what were he doing i just saw that he is using ctx.message.author so i say to use ctx.author
ctx.author is just a shortcut for ctx.message.author
ikr
you cant use self in the deco since you declare self in the function initiator, you are able to use the variables for the class which you set in the init function of the class
class uwu:
def __init__(self):
self.uwu = "uwu"
def foo(self):
print(self.uwu) ```
an uwu class
aw
with an uwu attribute
uwu.uwu moment
lmao
the class doesn't have any variables
it had attributes 🥴
i have a uwu wave
uhhhh same thing
I know that
UwU
uwu gonna become an adjective and an adverb soon 😔
uwu will take over "test"
no
class MyClass:
variable: str = "variable"
def __init__(self):
self.attribute = "attribute"
``` not really but yeah
I wish an uwu langauge to exist too
thats why i like you more than hunter loll
well
!ot thanks (:
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
Well who cares what we call it, they function same
🏃
xD yeah
Is there something like interaction.id
I switched from discord.ext to slash commands and before I use to use ctx.author.id
But there’s none for interaction
discord
I’m using Nextcord……
..
why did you ask if you dont wanna listen?
I mean nope as In it won’t work
well, dont expect to get helped then if you wont even listen
First of all, what library are you using?
Im listening
interaction.author is a disnake property..
doesnt it have an author alias?
or nextcord is that shit
.user, comes from original discord.py
The user or member that sent the interaction.
You can access the id from this
Nextcord “”
I want to make a confirm button for a selection menu how do I get he selected value from the selection menu by clicking on the button ?
select.values[0]
How do I get a the value from clicking on the button ?
umm, ur supposed to link callbacks for each button
Yes
so what value are you trying to get?
The value from the dropdown
thats the select menu
Yes
u get values like that ^^
select.values gives u a list of all the opitons selected
[0] will give u the first one
which i assume is what you want
Good noon, I'm currently using cogs for my bot. I have one with admin command, such as changeprefix. Therefore I have a file called prefixes.json to store the prefix data for each server the bot is on. But how can I then grab this value to use it as the bot command without changing the config.json file?
Ik that but I want to make a confirm button therefore I need to get the value from the dropdown from clicking on that button
get the value, store it in a variable or something, and then add it to the button
So that is the only way to do it ? Thank you
config = fetch('config')
print("Logging in!")
bot = commands.Bot(command_prefix=config["prefix"])
for file in os.listdir("./cogs"):
if file.endswith(".py"):
name = file[:-3]
bot.load_extension(f"cogs.{name}")
try:
bot.run(config["token"])
except Exception as e:
print(f'Process canceled: {e}')```
That's the main file that launch everything
@bot.slash_command(description="Top")
async def hvtrend(ctx):
await ctx.defer()
page = requests.get('')
tree = html.fromstring(page.content)
user = ctx.user
for i in range(1, 5):
link = f'' + tree.xpath(f"/html/body/div/div/div/div/main/div/div/div/div[3]/div/div[{i}]/a/@href")[0]
await user.send('\n'+link)
i am trying to take top 5 links from a website, the links are coming in 1 by 1 and i want them to come in 1 message like
link1
link2
why don't you put ctx.send inside the loop?
wait you did
ho sorry I missunderstood your question
you could str format with list
its alright basically this is what i need
link1
link2
not like
!d intents
u can use ctx.user.send
!d discordpy.intents
so you append the link to a list and then use that formating inside the ctx.send()
@slate swan
thank you
I'm currently using cogs for my bot. I have one with admin command, such as changeprefix. Therefore I have a file called prefixes.json to store the prefix data for each server the bot is on. But how can I then grab this value to use it as the bot command without changing the config.json file?
config = fetch('config')
print("Logging in!")
bot = commands.Bot(command_prefix=config["prefix"])
for file in os.listdir("./cogs"):
if file.endswith(".py"):
name = file[:-3]
bot.load_extension(f"cogs.{name}")
try:
bot.run(config["token"])
except Exception as e:
print(f'Process canceled: {e}')```
That's the main file that launches everything
What does this error mean
The error is speaking
You are trying to use len () on a command
No
Then replit made some shit as it normally does
whats the code ?
I'm writing a method to add prefixes to the bot, but despite correctly adding the prefix it doesn't recognize it when I do the command
async def get_prefix(bot, message):
default_prefix = config["prefix"]
custom_prefix = prefixes[f"{(message.guild.id)}"]
return default_prefix + custom_prefix
bot = commands.Bot(command_prefix=get_prefix)``` well I made this and whats following is the prefix adding method
```python
@commands.command()
@commands.has_permissions(administrator=True)
async def addprefix(self, ctx, prefix):
""" Change bot's prefix """
prefixes = fetch('prefixes')
(prefixes[str(ctx.guild.id)]).append(prefix)
with open('prefixes.json', 'w') as f: #writes the new prefix into the .json
json.dump(prefixes, f, indent=4)
await ctx.send(f'Prefix added: {prefix}') #confirms the prefix it's been changed to
why do you send 3 words
just send the codes where the error is
it should tell you the line where the error occurs
There
you're making a function, a function and then use that function inside that function and apply random.choice
how is that supposed to work
Yes
!d random.choice
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
it returns a random element from a list
therefore it gets the len of that said list
your function is a command and you're applying a list operator on it
yup I can confirm lol
How can I make a close button in the ticket channel?
What's your indentation
Ye I was also confused
that's a lot of async def
indentations
So I can make it without async def?
!d indentation
Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements.
Tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation.
?
Not sure why you are doing multiple async def
So it creates a ticket channel
(embed=em) theres also no em
wdym
Read your code
because you're compparing a int to a string.
You're in VS code apparently when you see a little wavy line under your code that means there is a problem
oh ok ty
why are you putting the channel id as a string?
I wrote this so I can use em instead of embed
passing your mouth on top of it can tell you what's wrong
idk haven't coded in python in a while xd
!e ```py
x = 5
y = "5"
print(x==y)
@spring flax :white_check_mark: Your eval job has completed with return code 0.
False
what is em
embed = em
oh
You did # before your line
O I forgot to delete it
yes
And fix your indentation please
So I don't need this line right?
idk what you're doing with that
it's up to you
where and how
I think its correct
should be
You can if you use it
Send a ss
like this?
What does this mean?
category = client.get_channel(id_here)
for channel in category.voice_channels:
await channel.delete()
change voice to text
How can i define it
im trying to make a on_message event that sends out server name, but it doesnt seem to work

It'd be really hard for you to make what you want using discord.py when you don't even know how to define a variable's value
on_message only takes one arguemnt, message
I never used cogs before
Erm it's not like that
All I need is a join command
This has nothing to do with cogs
Your define is useless if you aren't using it
is there any way to send embed alongside with it?
Yes
message.channel.send()
Yeah i'm not helping anymore
I literally wrote your code and fixed your errors before
And you haven't learned even basic python
Why are you trying to use cogs ?
Idk
And your error is what Cane said basic python
You're skipping the basics to do something advance that will bite you in the ass
Before using cogs I made a bot without any, I then switched to cogs after properly constructing my commands
lmao skev
The line:
cogs = []
``` Can you tell me why you got that @formal basin
Hello ashley
but want it to show the server name too and that needs ctx right
I deleted my cogs
whats the full name
async def ticketcreate(ctx):
button1 = Button(label = "Ticket", style = discord.ButtonStyle.green)
button2 = Button(label = "Close", style = discord.ButtonStyle.red)
async def button_callback(interaction):
category = discord.utils.get(ctx.guild.categories, name="Tickets")
ticket_channel = await interaction.guild.create_text_channel(name="ticket", category=category)
await ticket_channel.set_permissions(interaction.user, read_messages=True, send_messages=True, read_message_history=True)
await ticket_channel.edit(permissions_synced=True)
async def button2_callback(interaction):
await interaction.guild.delete_text_channel(ticket_channel)
button1.callback = button_callback
button2.callback = button2_callback
view = View()
view.add_item(button1)
view.add_item(button2)
await ctx.send(embed = discord.Embed(title = "Ticket", description = "Create a ticket"), view = view)
embed = discord.Embed(title="New ticket from {}#{}".format(ctx.author.name, ctx.author.discriminator), description= "Please wait, we will be with you shortly!", color=0x00a8ff)```
why isnt this working?
CokeCane
heya skevvv
CokeCane
You can just yoink the ctx out of it
kewl
All I need is a bot that joins the vc your in
It's literally just ctx.message.guild.name
bad indentation
dude, the second callback is inside the first one, watcha doing
how do I make this into a datetime.datetime object? time_online = datetime.datetime.utcnow() - self.start_time
Where self.start_time is a datetime.datetime.utcnow()
That’s what my command
ahh lemme try
async def get_prefix(bot, message):
default_prefix = config["prefix"]
guild = message.guild
if guild:
return prefixes[f"{guild.id}"]
else:
return default_prefix```
I want to make a custom prefix, **the prefix changes in the json file but the bot doesn't recognize it**, any idea why?
@modest harbor also
nothing happens basically
you get a timedelta object since its a difference between 2 datetimes, why would you need a datetime for that
Won't work cause it's message.content.startswith
is there any other ways to do it?
I want to put it into a disnake.utils.format_dt
To do what?
idk what to do
can you please help me
use startswith
sends the server name
sends embed
why dont you just format the self.start_time, there's a format which will show "x minutes/hrs/days ago"
should I make ticket_channel global variable
async def button_callback(interaction):
category = discord.utils.get(ctx.guild.categories, name="Tickets")
ticket_channel = await interaction.guild.create_text_channel(name="ticket", category=category)
await ticket_channel.set_permissions(interaction.user, read_messages=True, send_messages=True, read_message_history=True)
await ticket_channel.edit(permissions_synced=True)
async def button2_callback(interaction):
await interaction.guild.delete_text_channel(ticket_channel)
fuck, discord sux
botvariable
Use commands
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
anyone ?
can you show your bot constructor
iirc u need to re read the json file
does your json save the guild ids as string?
config = fetch('config')
prefixes = fetch('prefixes')
print("Logging in!")
async def get_prefix(bot, message):
default_prefix = config["prefix"]
guild = message.guild
if guild:
return prefixes[f'{guild.id}']
else:
return default_prefix
bot = commands.Bot(command_prefix=get_prefix)```
^^^
yes:
{
"464553751030661120": "$",
"929126352437772358": ">"
}```
right
oh got it. Also do you know why it returns a tuple?
how so?
the timedelta? or format_dt?
Not sure what does that mean
you have with open("a json file") as file: type of thing somewhere?
more it inside get_prefix function
so it actually returns the wrong time
class Bot(commands.Bot):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.start_time = datetime.datetime.utcnow()
@property
def _uptime(self):
bot_uptime = disnake.utils.format_dt(self.start_time, "R")
return bot_uptime
imagine reading a json file every single message, not uwu
yes
def fetch(filename: str):
""" Fetch file """
try:
with open(f'{filename}.json', encoding='utf8') as data:
return json.load(data)
except FileNotFoundError:
raise FileNotFoundError("JSON file wasn't found")```
it's a function I use everywhere lol
So I don't have to type it all the time
call the fetch function inside get_prefix
shouldn't it restart when bot restarts?
it should
it returned 4 hours ago in the timestamp when it was a few seconds
it works amazingly !
because its saving utcnow maybe
pleasure
ah so i guess i should subtract them because that works
do you know how to make a timedelta into a datetime.datetime?
you want to add/subtract it somewhere?
yeah
you can add datetimes and timedeltas
yeah but if i do time_online = datetime.datetime.utcnow() - self.start_time this returns a timedelta
async def ticket1(ctx):
button1 = Button(label = "Ticket", style = discord.ButtonStyle.green)
button2 = Button(label = "Close", style = discord.ButtonStyle.red)
async def button_callback(interaction):
category = discord.utils.get(ctx.guild.categories, name="Tickets")
ticket_channel = await interaction.guild.create_text_channel(name="ticket", category=category)
await ticket_channel.set_permissions(interaction.user, read_messages=True, send_messages=True, read_message_history=True)
await ticket_channel.edit(permissions_synced=True)
async def button2_callback(interaction):
await interaction.guild.delete_text_channel(ticket_channel)
button1.callback = button_callback
button2.callback = button2_callback
view = View()
view.add_item(button1)
view.add_item(button2)
await ctx.send(embed = discord.Embed(title = "Ticket", description = "Create a ticket"), view = view)
await ctx.send(embed = discord.Embed(title="New ticket from {}#{}".format(ctx.author.name, ctx.author.discriminator), description= "Please wait, we will be with you shortly!", color=0x00a8ff))```
Why isn't this working?
bad indentation
I fixed it
@sullen pewter
@client.command()
async def ticket1(ctx):
button1 = Button(label = "Ticket", style = discord.ButtonStyle.green)
button2 = Button(label = "Close", style = discord.ButtonStyle.red)
async def button_callback(interaction):
...
async def button_callback2(interaction):
...
await ctx.send()
await ctx.send()``` this is smthing you have
the 2nd callback is inside the 1st one
and other parts too
well you cannot change a timedelta to datetime
since that literally means difference in time
oof then do you have alternatives?
async def ticket1(ctx):
button1 = Button(label = "Ticket", style = discord.ButtonStyle.green)
button2 = Button(label = "Close", style = discord.ButtonStyle.red)
async def button_callback(interaction):
category = discord.utils.get(ctx.guild.categories, name="Tickets")
ticket_channel = await interaction.guild.create_text_channel(name="ticket", category=category)
await ticket_channel.set_permissions(interaction.user, read_messages=True, send_messages=True, read_message_history=True)
await ticket_channel.edit(permissions_synced=True)
async def button2_callback(interaction):
await interaction.guild.delete_text_channel(ticket_channel)
button1.callback = button_callback
button2.callback = button2_callback
view = View()
view.add_item(button1)
view.add_item(button2)
await ctx.send(embed = discord.Embed(title = "Ticket", description = "Create a ticket"), view = view)
embed = discord.Embed(title="New ticket from {}#{}".format(ctx.author.name, ctx.author.discriminator), description= "Please wait, we will be with you shortly!", color=0x00a8ff)```
what are you trying to do?
a bot that creates a channel and send a message with 1 button
get the bot uptime in a markdown timestamp
But to create a channel it need to press the button
lemme test smthing wait
How do you even get the markdown timestamp in discord.py
is it possible to do error handling for a specific cog?
Pretty sure yes
!e py from datetime import datetime as d print("<:t:{}:R>".format(int(d.utcnow().timestamp())) print("<:t:{}:R>".format(int(d.now().timestamp())))
@slate swan :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | print("<:t:{}:R>".format(int(d.utcnow().timestamp()))
003 | ^
004 | SyntaxError: '(' was never closed
eh
async def ticket1(ctx):
button1 = Button(label = "Ticket", style = discord.ButtonStyle.green)
button2 = Button(label = "Close", style = discord.ButtonStyle.red)
async def button_callback(interaction):
category = discord.utils.get(ctx.guild.categories, name="Tickets")
ticket_channel = await interaction.guild.create_text_channel(name="ticket", category=category)
await ticket_channel.set_permissions(interaction.user, read_messages=True, send_messages=True, read_message_history=True)
await ticket_channel.edit(permissions_synced=True)
async def button2_callback(interaction):
await interaction.guild.delete_text_channel(ticket_channel)
button1.callback = button_callback
button2.callback = button2_callback
view = View()
view.add_item(button1)
view.add_item(button2)
await ctx.send(embed = discord.Embed(title = "Ticket", description = "Create a ticket"), view = view)
embed = discord.Embed(title="New ticket from {}#{}".format(ctx.author.name, ctx.author.discriminator), description= "Please wait, we will be with you shortly!", color=0x00a8ff)```
will this work now?
you should run and check
view.add_item(button1)
view.add_item(button2)
u already added both buttons to the view
what do you expect??
what should I do then
001 | <t:1649588546:R>
002 | <t:1649588546:R>
which one's more accurate?
the same i guess
dont add both buttons to the view, add the second one in a diff view and send that in the new channel
the first one is a utcnow and the second one is a now
how can I add it in different view
but it gets adjusted to user's tz
view2 = View()
view2.add_item(...)
Define what ban is
well, did u define ban?
...
Hey, I'm getting a "There is no current event loop in 'Thread-3 (start)'." error. I know that I have to create a new asyncio event loop but I'm not sure how that will work in my current use case
def main():
threading.Thread(target=func1.start).start()
threading.Thread(target=func2.start).start()
@tasks.loop(seconds=3)
async def func1():
# do stuff
@tasks.loop(seconds=8)
async def func2():
# do stuff
``` This is the format of my code for now
raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'Thread-3 (start)'.
python doesn't have afunction called ban
This is not a Modmail thread.
Use the documentation to find out how to ban someone I'm not that fluent lol
anyone?
Then define it in a variable
The way to start a task is just Task.start(), you don't need to use threading or whatever it is.
I need the tasks to be in threads
I already asked the question in a help channel, no one aswered
Because if i just do py func1.start() func2.start() func1.start() will block func2.start()
and this is the code for a discord bot
It doesn't, it's how async and concurrency works
Well, thanks to anyone that helped me with the issue I got, I finally finished making my bots and that wouldn't have been without your help so thanks a lot!
omg thanks it worked
How do I move the dropdown to be above buttons ?
^^
How do I do that ?
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
Does anyone know how i could make a logging channel system?
For example:
I have finished with a ticket, i rename it to foxx-done, then the bot will edit an existing message with the stats of all the tickets i have completed, so it would be foxx: 1 then if i did it again it would be foxx: 2 and so on.
I’m think of using a json file to log the users but i’m not sure how to do this, any ideas?
There's a parameter named row on ui.Select, set it to 0 and it should be above the buttons
anyone know how to implent this as verification on a discord server?
1 or 0?
Modals
!d disnake.ui.TextInput
class disnake.ui.TextInput(*, label, custom_id, style=<TextInputStyle.short: 1>, placeholder=None, value=None, required=True, min_length=None, max_length=None)```
Represents a UI text input.
This can only be used in a [`Modal`](https://docs.disnake.dev/en/latest/api.html#disnake.ui.Modal "disnake.ui.Modal").
New in version 2.4.
what?
0
why are you passing the __repr__ of an instance
Where it says syntax error
<ButtonStyle.secondary: 2>
you can just style=2
you just pass ButtonStyle.secondary
Or style = ButtonStyle.secondary so people can actually read
.red
...
import it
!d discord.ButtonStyle
class discord.ButtonStyle```
Represents the style of the button component.
New in version 2.0.

