#discord-bots
1 messages · Page 290 of 1
bat script or python script to close the bot?
simplest way is just make a task and call bot.close after half an hour
idk how to make a timer 😭
await asyncio.sleep(60 * 30) # sleep 30 mins
await bot.close()
make a task and call it in setup hook
!d asyncio.create_task
asyncio.create_task(coro, *, name=None, context=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task) and schedule its execution. Return the Task object.
If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name).
An optional keyword-only *context* argument allows specifying a custom [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context) for the *coro* to run in. The current context copy is created when no *context* is provided.
The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError) is raised if there is no running loop in current thread.
Note
[`asyncio.TaskGroup.create_task()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup.create_task) is a newer alternative that allows for convenient waiting for a group of related tasks.
this is how to make a task?
thats basic async python
i though it was just @client.setup_hook
no?
setup_hook takes in a function dont think you can use it as a decorator
my point is make a function with those two lines above and call it using create_task
There’s also a tasks extension with discord.py
await asyncio.sleep(1) that 1 is a second right?
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
print(f"started at {time.strftime('%X')}")
await say_after(1, 'hello')
await say_after(2, 'world')
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
i dont understand it
async def say_after(delay, what): what is that arg "what"
WHY DO U NEED IT
PLUH🗣️
Here it's to give message to print out later
then my code will not run 💀
cant i just make a timer with time
You can.
But your bot will go offline for the time you will sleep with time
i have intermediate experience w/ python but not the discord package. for some reason my code isnt working? i think i setup wrong?
from discord.ext import commands
intents = discord.Intents.default() # This creates a default set of intents
intents.messages = True
client = commands.Bot(command_prefix = '!', intents=intents)
# waiting for bot to be ready for use
@client.event
async def on_ready():
print("Bot is ready :)")
# a command whenever a client types in "hello" it calls the "hello" func
@client.command()
async def hello(ctx):
await ctx.send("hello, i am kenneth pause")
client.run("here is my token i am assuming")```
is this fine? i was following some tutorial
The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."
The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.
Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:
intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents
bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor
For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.
and for some reason whenever i type in the command !Hello its not working
^ Zeny
its hello not Hello with a capital
Also true
intents = Intents.default()
U are missing an intent read the embed above
intent.message_content
not messages
also try this
@client.command()
async def test(ctx):
await ctx.send("RUNNING")```
intents.message_content = True # enable message content ```
so like this?
Try and see
i did but i get an error 😦
Then show the error
ohhh wait i didnt enable it
intents = Intents.default()
It's ok shouldn't matter
The thing you are trying to do requires you to import Intents from discord
where can i enable privileged intents on discord developers?
The error should have given you the link to dev portal
bot section
oh shit nvm im stupid
you didnt import intents btw
It's fine he doesn't need to
its working is intents part of the discord package?
Yeah
@slow escarp
intents= discord.Intents.default() is same as
from discord import Intents
intents= Intents.default()
intents.message_content = True # enable message content
client = commands.Bot(command_prefix = '!', intents=intents)```
i tried asking chatgpt what this does but i think the discord package might have updated after 2021 since chatgpt is saying this is wrong. what does this do?
if you dont import intents client = commands.Bot("!",intents=intents) doesnt work
Why wouldn't it?
Gpt is shit
dont hate on it its saved me so much time 🙏
intents = intents how does it know what it intents
If you defined it, it doesn't matter what you import
intents is an argument of commands.Bot class
It's the truth especially when it comes to discord bot coding
Most of it's knowledge is old
And d.py has changed too much
mmm okay what does intents mean and do though?
if i dont import it NameError: name 'Intents' is not defined
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
Intents are a feature of Discord that tells the gateway exactly which events to send your bot (copy pasted)
It will since you need to access Intents from discord
So it should be
discord.Intents...
That's normal when you don't have something defined 🤷
how do i make slash commands?
Which lib?
wym?
Library
discord.py or nextcord
What library are you using?
i think
oh discord.py sorry i was not thinking lmao XDD
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
ty i will try!
Welp read it carefully
i will!
Since it contains almost everything you require to create and use slash command s
dpy's still alive wtf 💀
and 2.0**+** wow
2.3.2
don't question it if it works don't touch it
Didnt know jishaku can do that
what's there that shouldn't work
It runs the code @buoyant quail.icon.url with getting the actual member
You know jishaku?
!pip jishaku
A debugging and testing cog for discord.py rewrite bots. - GitHub - Gorialis/jishaku: A debugging and testing cog for discord.py rewrite bots.
A discord.py extension including useful tools for bot development and debugging.
more japanese named cool shit
can someone help me with my slash commands? discord.py
Hi guys !
This question concerns Discord API but not bots, although I still think I should post it here.
I'm trying to get user informations from a user id and according to discord api reference, I have to set up my oauth 2.0 token which I did. The following request works like a charm:
https://discord.com/api/v10/users/@me and the ressource server responds with all my informations.
However when I replace @me with a user_id it responds with a 401 unauthorized error, which is not supposed to happen according to discord api reference.
Anyone has a tip about that? I'm still new to oauth and api requests so I got quiet lost
well I suppose it is
not reading allat on phone
I'm trying to put a thumbnail on discord.Embed object. The url I'm trying to set requires cookies in order to fetch the image.
I thought of two options:
- Download the image in a local directory and put it on the embed.
- Send the image using
discord.File(BytesIO(requests.get(url, cookies=cookies).content), filename=filename), get the image url from the sent message usingmessage.attachments[0].url, and put the url todiscord.Embed().set_thumbnail().
Is there any other way? I don't want to download or send the actual image before the process.
UPDATE:
It worked by trying
headers: {
Authorization: `Bot ${token}`
}
Instead of
headers: {
Authorization: `Bearer ${token}`
}
(Both are of course not the same tokens one being the api token from the application oauth 2.0 request, and the other being the bot token)
However I'm still not understanding why it doesn't work with the first way as it's supposed to :/
Why do you need to give it cookies anyway? 
why do i need to add fallback with this? @client.hybrid_group(fallback="info")
I didn't make the system which I'm trying to fetch images from. It just works that way...
Because you need it it seems
It's optional /
if i dont do it it gives me errors that i dont have a signature
You can do something like How do I use a local image file for an embed image?, but use the file that you get from your request instead of a local file
Where
Show code + error
the error: ```2023-08-22 20:37:17 ERROR discord.app_commands.tree Ignoring exception in command tree
Traceback (most recent call last):
File "C:\Users\Flori\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 1089, in wrapper
await self._call(interaction)
File "C:\Users\Flori\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 1221, in _call
command, options = self._get_app_command_options(data)
File "C:\Users\Flori\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 1153, in _get_app_command_options
raise CommandSignatureMismatch(command)
discord.app_commands.errors.CommandSignatureMismatch: The signature for command 'server' is different from the one provided by Discord. This can happen because either your code is out of date or you have not synced the commands with Discord, causing the mismatch in data. It is recommended to sync the command tree to fix this issue.
code: ```@client.hybrid_group()
async def server(ctx):
guild = ctx.guild
if guild:
embed = discord.Embed(title=f'Server Info - {guild.name}', color=discord.Color.blue())
embed.add_field(name='Server ID', value=guild.id, inline=False)
embed.add_field(name='Owner', value=guild.owner.mention, inline=False)
embed.add_field(name='Member Count', value=guild.member_count, inline=False)
await ctx.send(embed=embed)
else:
await ctx.send("This command can only be used in a server.")```
Just your commands are not synced?
well it is
(also, it's a good idea to use an asynchronous http client, like aiohttp instead of a synchronous one, like requests)
Sync it again
i used this code to sync it ```@client.command()
@commands.guild_only()
@commands.is_owner()
async def sync(
ctx: Context, guilds: Greedy[discord.Object], spec: Optional[Literal["~", "", "^"]] = None) -> None:
if not guilds:
if spec == "~":
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "":
ctx.bot.tree.copy_global_to(guild=ctx.guild)
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "^":
ctx.bot.tree.clear_commands(guild=ctx.guild)
await ctx.bot.tree.sync(guild=ctx.guild)
synced = []
else:
synced = await ctx.bot.tree.sync()
await ctx.send(
f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
)
return
ret = 0
for guild in guilds:
try:
await ctx.bot.tree.sync(guild=guild)
except discord.HTTPException:
pass
else:
ret += 1
await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")```
tried multiple times
Wait some time after syncing ¯_(ツ)_/¯
it only works when i add fallback="info"
Please don’t name your bot client, it’s extremely misleading
should work almost instantly
uhhh sure
bruuhhh why doesnt it work 💀
That is interesting. Thank you.
I guess you had it before and it is still the synced version
na because if i add that then it will be /server info and now its /server so it did sync
hybrid_group works absolutely fine without fallback by me (and it should)
can u test my full code?
import discord
from discord.ext import commands
from typing import Union, Literal, Optional
from discord.ext.commands import Greedy, Context
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
intents.bans = True
intents.guilds = True
intents.reactions = True
intents.presences = False
bot = commands.Bot(command_prefix="$", intents=intents)
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Game(name="test"))
print("Bot started succesfully!")
@bot.hybrid_group()
async def server(ctx):
guild = ctx.guild
if guild:
embed = discord.Embed(title=f'Server Info - {guild.name}', color=discord.Color.blue())
embed.add_field(name='Server ID', value=guild.id, inline=False)
embed.add_field(name='Owner', value=guild.owner.mention, inline=False)
embed.add_field(name='Member Count', value=guild.member_count, inline=False)
await ctx.send(embed=embed)
else:
await ctx.send("This command can only be used in a server.")
@bot.command()
@commands.guild_only()
@commands.is_owner()
async def sync(
ctx: Context, guilds: Greedy[discord.Object], spec: Optional[Literal["~", "*", "^"]] = None) -> None:
if not guilds:
if spec == "~":
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "*":
ctx.bot.tree.copy_global_to(guild=ctx.guild)
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "^":
ctx.bot.tree.clear_commands(guild=ctx.guild)
await ctx.bot.tree.sync(guild=ctx.guild)
synced = []
else:
synced = await ctx.bot.tree.sync()
await ctx.send(
f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
)
return
ret = 0
for guild in guilds:
try:
await ctx.bot.tree.sync(guild=guild)
except discord.HTTPException:
pass
else:
ret += 1
await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")
with open("token.txt", "r") as token_file:
token = token_file.read().strip()
bot.run(token)```

hybrid_group shouldn't be a command
wym by that?
you are making it as server is a command
it shouldn't be
group server means that you have commands like server something not just server
how do i fix it then? (should be serverinfo)
fallback adds an extra command
but hybrid alone doesnt work
ooooooooh
@buoyant quail ty XDD
@buoyant quail do i need to resync the bot every time it joins a server?
no
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
oh okay!
guys this codes why doesnt work:
@bot.hybrid_command()
async def naber(ctx):
await ctx.reply("hi")
@bot.tree.command()
async def aber(interaction: discord.Interaction):
await interaction.response.send_message("hi1")
Did you sync the commands?
idk how can ı
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
yes its for example
I can't understand what he meant
Described what slash panel is
Or, if you mean the whole question - the commands don't show up
xd idk how can ı mean it
That i got decapitated
Got this error:
Traceback (most recent call last):
File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\simoc\OneDrive\Desktop\Comune di Roveto\DiscordBot\Comune di Roveto, Regione Toscana V2\bot_v2.py", line 45, in on_message
if message.attachment:
^^^^^^^^^^^^^^^^^^
AttributeError: 'Message' object has no attribute 'attachment'
I'm trying to see if a message has a photo or not.
The code i actually have:
@bot.event
async def on_message(message):
if message.attachment:
await message.channel.send(content=message.attachments[0].url)
!d discord.Message
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the message’s hash.
Look what attributes it has
Message object does not have .attachment attribute
You can find list of what attributes it has here
Is this legal?
ye (ig)
idk
out of interest why would you want your bot to join servers for you
yeah and that's oauth
u add those scopes to the bot when requesting oauth and granting perms
some bots add it in their request scope to add the user to their official server from website login
you create an oauth flow
meaning u make some sort of dashboard website
its in discord developer docs
Requests?
just check the oauth section
In discord developers or where?
How to use it?
I just saw it in the oath generator
But no explain how to use it in the project
Like nextcord?
Raw requests : )
Requests need to access for token
Nope
There is something called user key or IDK what is but when the user authorize in a bot have a condition of join servers for you you can get it
Maybe some another key, doesn't matters
What will be the difference between raw requests and something else
If libraries are just sending requests
When someone athorize in the bot, you get this thing
brooooo
How is this in discord and doesn't exist in discord libraries?
This is public thing
you mustn't share these things
That's not main
It's public project
But you can't make any thing with this
Cause this users didn't authorized in your bot
They are in some libraries i believe. But not in bots libraries
You never used this before?
Nope
Yeah, it doesn't seem popular
The most popular library i found has 16 stars
Can you give it to me?
- is there a way to convert a JavaScript code to Py
Cause there are too many bots using this but all of them in JavaScript
rewrite by hands
IDK anything in java
it's kinda same
I saw something called js2py
from what i see it can only execute it and extract resulting output, variables and so on
not make a python code
HAHHAHAH
lmao
i found some "Online JavaScript to Python Converter"
XDDD
Not working in big codes
not working at all
There are probably transpilers that might do a better job
But would recommend just writing it by hand
How to make this when you don't know any thing in java?
You do
You already know variables, some operations with numbers, strings and so on
But nothing in discord bots
And I see a wired things
Like variable start with var
And why every line in code start with consest or IDK what
And what will it break for you

But not a full language
that's true
but a lot of it already
and a lot of things just have some different syntax, but are also same
😂 .
async def gpt4(interaction: discord.Interaction, query: str, context: Literal['8k', '32k']):
how can I make the context option optional?
Default would be 8k then?
just set default value
yep
how to do that
def f(arg: str = "default")
thank you
yo is there a reason that in discord.py this code isn't working?:
@bot.event
async def on_member_update(before, after):
print(after.activities.CustomActivity.name)
the bot has the right intents, is only in my server, and i've changed my status and nothing changes
@slate swan Downie
?
Using threads?
!d threading.Thread
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)```
This constructor should always be called with keyword arguments. Arguments are:
*group* should be `None`; reserved for future extension when a `ThreadGroup` class is implemented.
*target* is the callable object to be invoked by the [`run()`](https://docs.python.org/3/library/threading.html#threading.Thread.run) method. Defaults to `None`, meaning nothing is called.
*name* is the thread name. By default, a unique name is constructed of the form “Thread-*N*” where *N* is a small decimal number, or “Thread-*N* (target)” where “target” is `target.__name__` if the *target* argument is specified.
*args* is a list or tuple of arguments for the target invocation. Defaults to `()`.
*kwargs* is a dictionary of keyword arguments for the target invocation. Defaults to `{}`.
thats literally all i know about threads so cant really help more
Then what option do i have?
!d asyncio.create_task
asyncio.create_task(coro, *, name=None, context=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task) and schedule its execution. Return the Task object.
If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name).
An optional keyword-only *context* argument allows specifying a custom [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context) for the *coro* to run in. The current context copy is created when no *context* is provided.
The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError) is raised if there is no running loop in current thread.
Note
[`asyncio.TaskGroup.create_task()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup.create_task) is a newer alternative that allows for convenient waiting for a group of related tasks.
Though I am not sure if there's many good reasons for wanting to run two bots at once in the same process
Tried this ngl
This starts getting a bit deep into the event loop and asynchrony so would recommend getting comfortable before proceeding
the most straightforward is to just run the bots in their own processes separately
Oh
Show us your intents in the dashboard and pastebin your entire code please
ok will do in 5 mins when i have my laptop
you can use create tasks to create task handles and gather them perhaps
A specific image isn't loading in an embeds url, I don't know why but could it be too high quality?
The url is valid
I'm using
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
client.run is not a coroutine
You are going to run into the same issue as before
client.start waits for the duration of the bot
I'm confused
you can run only 1 bot per process
Not really it works and I'm figuring out how
Not really
You technically can but there's no point
https://paste.pythondiscord.com/ZHGA
got rid of quite a lot of the code as it contained sensitive info, and some variables are blank etc
any clue? @sick birch
fyi requests is blocking
!d aiohttp
coroutine async-with request(method, url, *, params=None, data=None, json=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, allow_redirects=True, ...)```
Performs an asynchronous HTTP request. Returns a response object.
I often have large texts like these in my embeds, how would yall recommend I format it to make it readable while not taking an entire page?
you can reduce number of Ls
this might be better displayed as an image-
The input varies a lot so it would be impossible to manually go through each output
It's just an example of the output
Like create an image with the text?
Make a diagram or whatever that's easy to read, or just format it nicely and get that as an image
I don't mean do this like programatically
Oh, it would have to be
There's millions of different outputs so it's impossible to anticipate
For a solution to work it would have to be 100% automatic, here's another example of a large output
wtf
It's scraping data off a website, that's why it's so weird
makes sense
And deleting the repeating words isn't a good solution either
i need someone to review this code ```py
@commands.Cog.listener("on_command_error")
@commands.Cog.listener("on_application_command_error")
async def log_exceptions(self, context: commands.Context | nextcord.Interaction, exception: Exception):
if isinstance(exception, commands.CommandNotFound):
return
if not isinstance(context, commands.Context | nextcord.Interaction):
raise TypeError(f"Unknown context type: {type(context)}")
if isinstance(exception, commands.CommandError):
exception = exception.original
if isinstance(context, commands.Context):
invoker = context.author
created_at = context.message.created_at
name = f"`{context.command.qualified_name}`"
_args = context.args[2:] # ignore self and ctx
_kwargs = context.kwargs
args = " ".join(_args + [f"{k}={v}" for k, v in _kwargs.items()])
elif isinstance(context, nextcord.Interaction):
invoker = context.user
created_at = context.created_at
name = context.application_command.get_mention()
_options = context.data.get("options")
args = " ".join(f"{option['name']}={option['value']}" for option in _options)
guild = context.guild
channel = context.channel
tb = "".join(traceback.format_exception(type(exception), exception, exception.__traceback__))
_log_channel = self.bot.get_channel(1096144011460358315)
embed = (
nextcord.Embed(
title="Exception occured!",
color=nextcord.Color.red(),
timestamp=created_at,
)
.add_field(
name="Invokation details",
value=(
"backticks...yaml\n"
f"Guild: {guild.name} ({guild.id})\n"
f"Channel: {channel.name} ({channel.id})\n"
f"Invoker: {invoker.name} ({invoker.id})\n"
"backticks..."
),
inline=False,
)
.add_field(
name="Command details",
value=(
f"**Command**: {name}\n"
f"**Arguments**: `{args}`\n"
f"**Executed at**: {format_dt(created_at)} ({format_dt(created_at, style='R')})\n"
),
inline=False,
)
)
if len(tb) < 4080:
embed.description = f"backticks...py\n{tb}backticks..."
await _log_channel.send(embed=embed)
return
await _log_channel.send(
"Traceback is too long to embed. Uploading as a file.",
embed=embed,
file=nextcord.File(StringIO(tb), filename="traceback.txt"),
)
if this is aliexpress- the colour names arent even accutate all the time either
what would you upgrade in it to make it more pythonic xd
well, pep 9001 compliance officer is here
ah hell nah not pep 9001
It's not Aliexpress but it's pretty similar sites
Chinese marketplaces
same point
pep 9001 style guide not using in this project yk yk
Yeah, I've noticed that as well
I've had to introduce a bit of hard coding as the headers for the sizes of the item vs the color aren't always accurate
For the majority of the items their IDs are 0 for color and 1 for sizes, but not all
So that messes it up
Why nextcord tho
Real question
just used to it for 2 years
when discord.py was discontinued i chose it and im still with it 🫡
I used disnake and migrated back after Danny said he was working on discord.py again
you see, i did not migrate
and im happy about it
i dont like how slash commands work in discord.py
Show an example of nextcord
@nextcord.slash_command(name="ping")
async def _ping(self, interaction: nextcord.Interaction):
await interaction.send(f"Pong! {round(self.bot.latency * 1000)}ms")
``` (this is in Cog)
normally you would do @bot.slash_command()
Looks pretty similar to discord.py
not really if you look at it
the main difference is that nextcord auto syncs
and i very like it
discord.py is the only framework i know that does not auto sync so
i dont know where this choice comes from
how often do you change slash signature that you need auto sync tho?
cool thing is that you can just do interaction.send(...) and it will work out if its first response (.response.send_message) or not (.followup.send)
Can somebody help with cogs? I keep getting No module named 'cogs' even tho I has such directory
GIT: https://github.com/scottarsenjr/webhooks/tree/master/directories/discord
for testing purposes, quite many times
i also add some commands to test if something works
Hello everyone!
especially when making error logger
where you get this error at?
run.py is main file
your cogs folder relative to your cwd is inside bot folder, so bot.cogs.<filename>
i do not know how making an error logger requires altering slash commands signature but sure
but where you try to import cogs
oh ok, but now i get this: discord.ext.commands.errors.CommandNotFound: Command "setup" is not found
auto sync do eats away API calls which i dont like
to run.py file, from bot/cogs
i was making it show what params were sent with command
So I’m hoping I can find someone who can help me on my journey to help a friend. Long story short, I have a friend that’s been in my clan for well over a year now. He is an older gentleman, doctors told him he had 2 weeks to live, and here we are 2+ years later, hanging out together and having late night chats.
But he can’t speak to me. So I’m always reading out his messages.
Is there any way to code a bot to automatically speak what is being sent in the chat boxes?
so had to change it few times
like flowery already said you need from bot import cogs absolute import
https://github.com/scottarsenjr/webhooks/blob/master/directories/discord/bot/cogs/setup_cmd.py#L36 bot.add_cog is async, you need to await it
directories/discord/bot/cogs/setup_cmd.py line 36
bot.add_cog(CogName(bot))```
I really want to figure something out for him. And he has such an amazing attitude towards it. He says he wants a voice like Stephen Hawkins or Nicolas Cage lol
if its discord.py but looks like it
he is awaiting the load_extension so
Thank you very much! 
true i keep forgetting this server have multiple types of discord.py forks
only if the bot have access to that text channel, you can just use on_message event
me when no reviews, bump 🤫
What if it was whatever voice channel we were hanging out in? I just don’t see any good tts bots :/
o, not sure i've never tried tts related things
Oh well. Thanks for the help! Will continue the search.
Yeah, it's possible
You would have to find an async text-to-voice library
!pip aiogTTS
Last commit was over a year ago so hopefully it's still working
Seems like files are being saved locally but since it's only for 1 person it doesn't seem like it'll be much of an issue
Run that in your ide
If this is about discord emojis: https://discordpy.readthedocs.io/en/stable/faq.html#how-can-i-add-a-reaction-to-a-message
It explains how to get string that will result in an Emoji on discord
I am trying to use the python emoji library to convert the shorthand to a unicode string that discord will accept
So far it is unclear what shorthand I actually need to use, I guess I can just skip that process and figure out the strings that discord requires
@ai.command(name="sdxl", description="Generate images with DALL-E")
@app_commands.describe(prompt = "The prompt to generate", width = "Width of the image", height = "Height of the image")
async def sdxl(interaction: discord.Interaction, prompt, width: Literal[512, 1024] = 512, height: Literal[512, 1024] = 512):
await interaction.defer(ephemeral=False)
try:
await interaction.send(sdxl(prompt, width, height))
except Exception as e:
await interaction.send(f"Cannot generate with SDXL. \n{e}")
traceback.print_exc()
E:\files\bot-py\extension\ai.py:42: RuntimeWarning: coroutine 'Command.__call__' was never awaited await interaction.send(sdxl(prompt, width, height))
why do I have to await sdxl?
import replicate
def sdxl(prompt, width, height):
output = replicate.run("stability-ai/sdxl:d830ba5dabf8090ec0db6c10fc862c6eb1c929e1a194a5411852d25fd954ac82",
input={"prompt": prompt, "width": width, "height": height}
)
image_url = output[0]
return image_url
Additional parameter has to be passed to get the desired result.
This emoji stuff isn't actually visible to me, but I can copy the bytes to a web converter to see if it worked.
Now I should be able to pass the UTF-8 string to discord
u have 2 functions
sdxl def and async
@obsidian fable rename the function ur calling
how to solve this error ?
Await the load_extension function
i've done that but still giving the same error
I meant this one
ohh okk my bad
like the colour scheme 👍
thanks btw if you want to use it the theme name is "One Dark Pro"
@naive briaris discord.py is discontinued?
no
it was discontinued but they started again the development
so for now what should i use like pycord or should i continue using discord.py?
discord.py is better
dpy
okay
can you help me in another thing like i wanna create a presonal music bot for my server so how to create it like i've searching for last 2-3 days but idk why all the ways are not working correctly, can you help me like how should i work on it?
look into soundcloud
some grayer areas are wavelink/lavarel
it uses ytdl underneath iirc tho 😔
When I make 2 checks like @has_role & @has_permissions The user of the command need to have them both
How I can make it should have only one
Like if you have the role without the permissions you can use it and if you have the permissions without the role also you can use it
!d discord.ext.commands.check_any
@discord.ext.commands.check_any(*checks)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is added that checks if any of the checks passed will pass, i.e. using logical OR.
If all checks fail then [`CheckAnyFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckAnyFailure) is raised to signal the failure. It inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
Note
The `predicate` attribute for this function **is** a coroutine.
New in version 1.3.
Is it a code block?
No
grid = [':smile: ',':red_x_cross: ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ' ,'💣 ','💣 ','💣 ','💣 ','💣 ']
already_used = []
the message
It is a code block
Id understan?
abc
is a code block
how to fix this?
no random select
Send it as just text
without backticks
mean this ```
One more no work why?
@buoyant quail
that was correct deinition of emoji by id
that is not
hello
code js bot = commands.Bot(command_prefix="+", intents=intents)
erreur js bot = commands.Bot(command_prefix="+", intents=intents) ^^^^^^^
help me plz
import intents
What it shows
bruh
Check the emoji id
No
For example 💀
1143818446635802644 Look
?
invite
Dm
fixed?
yes
disnake
disnake ftw imo
yeah
I have too problem. It say the token is invalid and intent are needed, but i check 10 times and all intent are correct and the token is correct
show code
can we add multiple button using discord.py in an embed?
Yes
can you tell me how ? please?
thanks
man how to i link change text like you?
Cool ty
show ur code
Ok, that actually crazy, when i start the bot and send a command on Discord, the Bot do nothing and the console give no error 🤔
u dont have an error handler
Maybe you didn't add any code except creating bot...?)
Show code
I have 2 Code, with commands and everything, both don't do anything
Show them
i can't send txt file bruh
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
^
put it here and paste the link
Just paste the link
alr
It says there in the embed
mh, don't understand
Then read it again
still don't understand
still, don't, understand
Then ask what exactly you don'y understand
everything :|
i've removed the on_message part and it works, with it, it doesn't work
Prefix commands are called from the on_message event
You did your own on_message event so nothing is calling the commands more
Link shows two ways to fix it
I can also give a third because you have a subclass:
class Bot(commands.Bot):
# your code ...
async def on_message(self, message):
await super().on_message(message)
# your code ...
mhh, but
class Bot(commands.Bot):
# your code ...
async def on_message(self, message):
await super().on_message(#what does this message mean?)
# your code ...
Call the original on_message method of the commands.Bot class
!e
class A:
def say(self):
print("A")
class B(A):
def say(self):
super().say()
print("B")
B().say()
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | A
002 | B
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Why can't I install "beepy" on Pycharm?
https://paste.pythondiscord.com/7NBA
building 'simpleaudio._simpleaudio' extension
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
[end of output]
So I cannot use Pycharm for it?
Wierd
Pycharm just uses your terminal
It doesn't do anything extra
You need to install what library need to be installed anyways
After that it will be possible to install it in pycharm too
!visual
ah bot dead ok
When you install a library through pip on Windows, sometimes you may encounter this error:
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
This means the library you're installing has code written in other languages and needs additional tools to install. To install these tools, follow the following steps: (Requires 6GB+ disk space)
1. Open https://visualstudio.microsoft.com/visual-cpp-build-tools/.
2. Click Download Build Tools >. A file named vs_BuildTools or vs_BuildTools.exe should start downloading. If no downloads start after a few seconds, click click here to retry.
3. Run the downloaded file. Click Continue to proceed.
4. Choose C++ build tools and press Install. You may need a reboot after the installation.
5. Try installing the library via pip again.
@young dagger ^
i couldnt run /tag command
skill issue 
blud you didnt know there is a tag for that
😰
A question is whether json is used as a database?
can you answer me ty
A lot of people use it but it is not database :p
So why is it?
if only my meta#217 was accepted i would simply send this command 
The many reasons why you shouldn't use JSON as a database, and instead opt for SQL.
..
I have a question, for example, if you use a command, can it be saved in json?
like date base
Because json is what people already know and it is just file
It doesn't require anything
Can you answer this.
what do you mean by save command as json
For example you use my command say /help
Convert to json.
json:
name: Down,
ID: 628951875147923476
No one will stop you from doing this
I know mean i can create on json
like datebase
what
It's not like a database, but it should be
json ~= dictionary/list
you can but is storing it in json file good option? prolly not
if you really wanna stick with json format check out Mongo DB
it uses Documents that are in json format
The many reasons why you shouldn't use JSON as a database, and instead opt for SQL.
Can you tell me the benefits of json?
i wanna add a function to my bot that whenever a new video get uploaded on my yt channel it will give a output
how do i do that
Json is used to either be only loaded once or as format
asnwer my question please
the google article sucks and is too much complitcated
first lern python
When you done
hahaha so funny
Lern discord or disnake
i cant stop laughing man
Yes, as a question
sommon if i didnt knew python why tf will i be on discord-bots section making discord bots
Your laughter will be stopped by cray
and i answer your question
If you knew, you would have made it and we would have fixed the error
what error?
That's a child's habit
Then we can help you if you have a problem with the code, not us creating it for you
i dont have a problem with code i just wanna know a good lib for getting notifies when i upload a new video gets uploaded on youtube
There is no benefit in Python. It's only used as a format not as file.
Then it's easy if you have the desire Good luck
That's good, c++ is not very beginner friendly but spending time programming is a good start.
thats the first language i learned when i was back in 4th grade but it was not easy it took me a while
i forgot it now because i didnt continue coding and just stopped
python very easy
You could also look into cpython or go if you like the stricter syntax.
If you learn python in my opinion
All languages will be easy
i like python syntax no ; no {} just peace
I don't agree with that.
Yes
html would be the easiest to start
Python is great for hacks
If you know both C and Java then you basically know almost every language. But then you also have SQL and other things.
Very easy
agreed
Learn brainfuck 
cool
you know?
Folder structure coding
you need to find some api to provide you such information
i'd even guess that it's youtube api
something like get all videos of author after some timestamp i guess
hello and t it possible to make a handlerd python? or do the commands only in the main.py
thats what i am asking
youtube api is there but there documentation is for all languages not python specific so its hard to understand and they barely tell what to do
?
then look for a youtube api wrapper in python
similar to how discord.py is a wrapper for the discord api
Could you elaborate?
!pypi python-youtube
I find out why. It use api v6
I've this piece of code, but for some reason, it completely resets my balance if I run it. What's the issue?
@bot.tree.command(name="deposit", description="Dump your cash in the bank")
async def deposit(interaction: discord.Interaction, amount: int):
async with bot.db.cursor() as cursor:
await cursor.execute("SELECT wallet FROM bank WHERE user = ?", (interaction.user.id,))
data = await cursor.fetchone()
if amount > data[0]:
await interaction.response.send_message("You not that rich.")
res = await update_bank(interaction.user, amount)
if res == 0:
await interaction.response.send_message("You don't have an account. Run `/balance` to create one.", ephemeral=True)
suc = discord.Embed(
title="Success!",
description=f"You deposited **${amount}** into your bank!",
color=discord.Color.green()
)
await interaction.response.send_message(embed=suc)
update_bank function:
async def update_bank(user, amount):
async with bot.db.cursor() as cursor:
await cursor.execute("SELECT wallet, bank FROM bank WHERE user = ?", (user.id,))
data = await cursor.fetchone()
if data is None:
await create_bal(user)
return 0
if amount > data[0]:
return 1
await cursor.execute("UPDATE bank SET wallet = ? AND bank = ? WHERE user = ?", (data[0] - amount, data[1] + amount, user.id))
await bot.db.commit()
this aint the package
!pypi google-api-python-client
this is the one
pretty sure there's different wrappers for different languages
... you mean languages as in programming languages, right?
yes
discord.py and discord.js would be different from each other
what language are you trying to use
you contradicted yourself
huh
documentation is for all languages not python specific
What are you looking for?
i am looking for a python sepcific documentatin
I won't question your weirdly worded question
simple thing google docs is confusing and dont give the answer as per shown and it dont show code so i cant test it or anthing neither pycharm shows it variable
"Intents" Object Has No Attribute "message_delete"
idk how to fix this
!d discord.Intents
class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).
New in version 1.5.
i dont see message_delete intent either
it's for my message log bot, is there a correct intent for message_delete?
disnake.ext.commands.errors.MissingAnyRole: You are missing at least one of the required roles: '<disnake.ext.commands.slash_core.InvokableSlashCommand object at 0x7f6421839910>' How can fix error>?
!d discord.Intents.messages i guess
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...
its in default intents anyway
my log thing isn't working, hm
what is not working about it?
it dosent send the message to the logs channel, when set
show code then
Give roles to the has_any_role and not a slash command
Even not roles but just the ids / strings
it doesnt entirely means that you are missing some intent
how can you even put slash command inside a check
@commands.command()
async def a(ctx):
...
@commands.command()
@commands.has_any_role(a)
async def b(ctx):
...
more like how can you put it here on purpose
we wont know until he provides code
He disappeared
xd

we are losing people
I checked my code and it still doesn't work
you checked it bad 👍
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
@bot.event
async def on_message_delete(message):
channel_id = retrieve_channel_id(message.guild.id)
channel = bot.get_channel(channel_id)
if channel is not None:
embed = discord.Embed(title="Deleted Message", description=f"Message deleted in #{message.channel.name}", color=discord.Color.red())
embed.add_field(name="Author", value=message.author.mention, inline=False)
embed.add_field(name="Content", value=message.content, inline=False)
await channel.send(embed=embed)```
retrieve_channel_id too
.get_channel can return None
huh
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.

I don't get it
to ensure you have the channel object use this: py channel = bot.get_channel(...) or await bot.fetch_channel(...)
if the channel is not found in the cache it will make api request to get it
NameError: name 'retrive_channel_id' is not defined```
idk 
but thats your own function?
mane idk, I tried coding it myself
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 3, in <module>
003 | if None + sex == None:
004 | ~~~~~^~~~~
005 | TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'
!e ```py
from fishhook import hook
@hook(type(None))
def add(self, other):
return
print(None + None)
@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.
None
Why does discord not make emoji only by id if it doesn't need the name?
 
 
so its readable
how do i make that it will open a link when i click on a button?
!d discord.ui.Button ^, since you can't use a decorator to make one
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.
i did this but not work
name="staff_logs",
description="Only satff can use it"
)
@commands.has_any_role(staff)
async def staff_logs (ctx, user: disnake.Member, id_member, timeout: staff_logs, rasson, date , by: disnake.Member):
await ctx.channel.send(f"{by}",embed=embed)
print(by,"Timeout member")
..............
how to fix?
@bot.slash_command(
name="staff_logs",
description="Only satff can use it"
)here?
@commands.has_any_role(staff)
yes. what is inside staff
I've done that before.
?
Now what i do?
answer my question finally 
what your quistion?
What is inside staff variable
And the error is the same as here?
yes
Press ctrl + f and search for def staff
..........
@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.
<function x at 0x7fbf3c7e0680>
man I don't want to change staff positions.
Just change the function's name then
Oh
yo, do you guys know how I would add a description for my hybrid_command? I don't want a description for the command itself, more like any arguments given to it
@bot.hybrid_command()
async def uptime(ctx):
await ctx.send(embed=discord.Embed(title="Uptime", description=f"{round(time.time() - st)} seconds", color=discord.Color.green()))
this is a bad example because theres no args in this command but if there was how would I do it?
!d discord.app_commands.describe
@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.
Example:
```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
await interaction.response.send_message(f'Banned {member}')
``` Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
!d discord.ext.commands.Context.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for non-interaction contexts.
For interaction based contexts this does one of the following...
ephemeral (bool) –
Indicates if the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes. This is only applicable in contexts with an interaction.
New in version 2.0.
Ephemeral where?
It’s a kwarg of Context.send
Didnt knew it had that arg, kinda cursed
.
It should get its own class tbh
Conteraction
code should document itself
did they reduce cooldown to 4 seconds
?
fr
5
did you know there is a name for such process or merging two words together
its called portmanteau 
is that a merged word too xd?
Port Man Tea You
makes sense
should i make my bot disable the button after some time? if so how?
ty
Is there anyway to center a field in an embed?
Pass empty fields
Set inline to true
You need invisible characters touch like ** **
No clue
I'll test it in a bit
is it possible to add a enter in here? async def invite(ctx):
like this but then want a enter in it @bot.hybrid_group(fallback="invite-removal") @commands.has_guild_permissions(administrator=True) async def invite(ctx): and without that fallback etc
wdym enter
a space i ment 💀 sorry
between the words
like: 'auto invite removal' and not like auto invite-removal
!d discord.ext.commands.command
@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command) or if called with [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group), [`Group`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Group).
By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str) using utf-8 encoding.
All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
kk
but i dont use discord.ext.commands.command
You're using slash commands?
ye
I don't believe it's possible then
huh but how do other bots have it then?
like i also cant use bot in async
Oh mb
!d discord.app_commands.command
@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
name arg
What
wdym
It'll have to be async or everytime something is run the entire bot will freeze
ik but i cant put "bot"in there for sum reason
and with this do i need to put it in the () from: @bot.hybrid_group?
or command
what
Share your code
@bot.hybrid_group(fallback="info")
async def alpra(ctx):
support = Support()
latency = round(bot.latency * 1000)
embed = discord.Embed(title="Bot Information", description="", color=0x009cff)
embed.set_author(name=bot.user.name, icon_url=bot.user.avatar.url)
embed.add_field(name="Bot ping", value='<@' + str(bot.user.id) + '>', inline=False)
embed.add_field(name="Bot ID", value=bot.user.id, inline=False)
embed.add_field(name="Latency", value=f"{latency} ms", inline=False)
creation_date = bot.user.created_at
embed.add_field(name="Creation Date", value=creation_date.strftime("%B %d, %Y"), inline=False)
embed.add_field(name="Creator", value="@sp1nkel", inline=False)
await ctx.send(embed=embed, view=support)```
like i couldnt do alpra bot info and bot info also doesnt work
I'm so confused lmao
Read the Github for examples on slash commands
I have a feeling you haven't worked with them before
was some time ago ye Xd and how was that github page named again?
They are subcommands
You don't make one command with spaces in it
ik that but that other thingy also didnt work
It's the discord.py Github page
Also for next time, the way you speak is incredibly confusing and hard to follow
can discord bots not play audio anymore?
im dyslectic ok :C
Doesn't dyslexia affect the way you read letters?
Hi. I have an idea, trying to find best way to implement.
My users have items. They can /use item (e.g. /use VoterChip).
I want to make a way to have items effect other commands..
Such as /use BlindChip will make the /rob command a 100% success.
How should I implement this? Is this ok:
Create a DB table (ex: ActiveItems), then when people /use these type of items, it'll be appended to the table.
Then in the commands, like /rob, it'll search table for that user and that item
Seems good enough
Having a DB of active buffs, then when the command (rob) is run checking those active buffs and altering the result
ooo, buffs, good term as well
thank u for the validation!
does anyone know why this is happening? I have a folder of functions in .\defs\, and I use for example from spotify_track import extract_first_artist_link to import functions from other files in the same folder
for other files I use for example from defs.spotify_artist import extract_artist_icon so that I can import but seems like I can't do that anymore?
from spotify_base import embed_scrape
ModuleNotFoundError: No module named 'spotify_base'
Hello I have a problem my ping command does not work can someone help me?
import discord
from discord.ext import commands
class ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print("Bot is online !")
@commands.command()
async def ping(self, ctx):
await ctx.send("Pong")
async def setup(bot):
await bot.add_cog(ping(bot))```
the problem is your indentation, you shouldn't be creating the command inside of the on_ready event
import discord
from discord.ext import commands
class ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print("Bot is online !")
@commands.command()
async def ping(self, ctx):
await ctx.send("Pong")
async def setup(bot):
await bot.add_cog(ping(bot))
```should look like this
TYYYYYYYYYYYYYYYYYYYYYYYYY
import discord
from discord.ext import commands
class Ping(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@commands.Cog.listener()
async def on_ready(self) -> None:
print("Bot is online !")
@commands.command()
async def ping(self, ctx: commands.Context) -> None:
await ctx.send("Pong")
async def setup(bot: commands.Bot):
await bot.add_cog(Ping(bot))
Superior
I already asked yesterday but I want to see if somebody has solution. My bot will often send large amounts of text with a lot of repeating words because it's coming from a websites json data, does anybody have any idea how I could dynamically reduce the amount of unneccesary words?
Those are some examples
I could also share the json data if somebody wants to help me figure out a different solution
file structs
Do you just want all the unique words?
Try
from defs.spotify_base import embed_scrape
it says def is not a package
I don't believe that would work as I want some repeating words to stay, I'm starting to believe it's not possible with my current implementation
Let me share the json data real quick
What says? Show the actual error
And defs
let me try again
discord.ext.commands.errors.ExtensionFailed: Extension 'extension.spotify' raised an error: ImportError: cannot import name 'download_track' from 'defs.spotify_base' (E:\files\bot-py\defs\spotify_base.py)
Are you sure that there is a download_track?
Show that file
import discord
from discord.ext import commands
class serverinfo(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print("commande serverinfo charger")
@commands.command()
async def serverinfo(self, ctx):
await ctx.send("Pong")
async def setup(bot):
await bot.add_cog(serverinfo(bot))```
can you help me ?
lmao
you can't always ask to indent your code
it's the most basic thing in python
bud, your indentation again is messed up
your serverinfo function needs to be inside of your serverinfo class, and btw, you have to rename either the class or function
because you cant have both with both names
why not
Can you explain to me because I am new to py and I saw a video cogs c so for that I do not understand
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
because when he'd be adding the cog it would most likely be trying to use the function & not the class due to them having the same name
maybe im wrong, not entirely sure just bad practice imo
Can you modify the code please?
The function will be method of the class so no
But yeah the naming isn't good
no, you need to learn, learn how to simply indent your code and have it inside of the class
ahh but either way its bad practice
!resources to learn python 
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
just look at the modified code i gave you originally, and see whats different
Right now I'm looping through ["prop_arr"]["propName"] to differentiate the names and the colors, then when I know it's a colour I access ["valueName"] and use that as the name
Here's a little snippet to show the structure: https://paste.pythondiscord.com/2CMQ
This is the entire JSON if you're willing to try and see if there's whole new way I could do it: https://paste.pythondiscord.com/G23A
@sick birch
The issue is, this has to be like 99% automatic
I could input the item id into a DB and when each command is run it'll check the item ID against the stored IDs, then execute the code to remove the excess letters
That would be possible, but I couldn't manually go through each individual link and choose the text
I don't understand 💀
@eager mural
It's not the same order bro
@final iron
huh
It's the exact same code, the class and function names are just different
Well, it is changed, the code is following pep8
Ohh thank
class ArtworkButton(ui.Button):
async def callback(self, interaction: discord.Interaction):
try:
result = songs_query(f"{artists} {name}")
print(result)
url = format_url(result)
await interaction.followup.send(url)
except Exception as e:
await interaction.followup.send(f"Cannot find artwork for `{name}`.")
traceback.print_exc()
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
which line is the error
Send the full traceback
Are you sure that it's already responded?
If interaction is not responded you'd get "Unknown Webhook" by trying to send followup
im pretty sure it is
There is not response here
Only followup
