#discord-bots
1 messages Β· Page 204 of 1
Do you have any other files?
acc wait
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
It doesn't seem like you even have a callback for your button
shall I add?
what's the problem here ```import discord
from discord.ext import commands
class cogs(commands.Cog):
def init(self, client):
self.client = client
def setup(bot):
bot.add_cog(cogs(bot))
@commands.Cog.listener()
async def on_ready(self):
print("cogs.py is ready!")
@commands.command()
async def embed(self, ctx):
embed_message = discord.Embed(title="Title of embed", discription="Discription of embed", colour=discord.Colour.orange)
embed_message.set_author(name=f"Request by {ctx.author.mention}", icon_url=ctx.author.avatar)
embed_message.set_thumbnail(ul=ctx.guild.icon)
embed_message.set_image(url=ctx.guild.icon)
embed_message.add_field(name="Field name", value="Feild value", inline=False)
embed_message.set_footer(text="This is the footer", icon_url=ctx.author.avatar)
await ctx.send(embed = embed_message)
async def setup(client):
await client.add_cog(cogs(client))
```
@sick birch ```[2023-02-26 22:57:23] [INFO ] discord.client: logging in using static token
[2023-02-26 22:57:24] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 21523dba6f5793dfde7b181d93a927c6).
Logged in as Blinded Tickets#7696
[2023-02-26 22:57:28] [ERROR ] discord.ext.commands.bot: Ignoring exception in command new
Traceback (most recent call last):
File "C:\Users\xavie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\xavie\OneDrive\Documents\kca.py", line 32, in new
view.add_item(button.with_callback(button_callback))
AttributeError: 'Button' object has no attribute 'with_callback'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\xavie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\xavie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\xavie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Button' object has no attribute 'with_callback'
Can you show your code?
yes
bro help me
Did you read the example? This isn't how you register a callback
button.with_callback??
check this out
@slate swan why don't you just use a class-based view instead???
class PurchaseTicketView(discord.ui.View):
@discord.ui.button(label = "Open Ticket", style = discord.ButtonStyle.green, custom_id = "open_ticket")
async def open_ticket(self, interaction, button):
...
lets see
then you do ```py
message = await ctx.send(
"my message",
embed = embed,
view = PurchaseTicketView()
)
also, why are you using both wait_for and a button?
don't they replace each other
???
nvm
yes, but if the user doesn't press the button it'll be inactive too
but let me try ur code.
right??
what's your code
What library is this
Then switch the button and interaction position in the callback argument
[2023-02-26 23:03:52] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 6a080f3c6f3c1f415eb57c801fa9e7e2).
Logged in as Blinded Tickets#7696
[2023-02-26 23:03:57] [ERROR ] discord.ui.view: Ignoring exception in view <PurchaseTicketView timeout=180.0 children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Open Ticket' emoji=None row=None>
Traceback (most recent call last):
File "C:\Users\xavie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "C:\Users\xavie\OneDrive\Documents\kca.py", line 15, in open_ticket
member = interaction.user
AttributeError: 'Button' object has no attribute 'user'
alr
@smoky sinew @naive briar ```Microsoft Windows [Version 10.0.19045.2604]
(c) Microsoft Corporation. All rights reserved.
C:\Users\xavie\OneDrive\Documents>kca.py
Traceback (most recent call last):
File "C:\Users\xavie\OneDrive\Documents\kca.py", line 19, in <module>
bot.add_view(PurchaseTicketView())
File "C:\Users\xavie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 190, in init
self.__stopped: asyncio.Future[bool] = asyncio.get_running_loop().create_future()
RuntimeError: no running event loop
C:\Users\xavie\OneDrive\Documents>```
and ill send code
I think I have to add a run() method.
That method need to be called in a async function
Like setup_hook
@slate swan if each user is going to run this command, then don't make the view persistent because it can use up a lot of resources
Hey @mild geode!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
add_view?
class TicketBot(commands.Bot):
async def setup_hook(self):
self.add_view(PurchaseTicketView())
then replace commands.Bot with TicketBot when you create it
This is my code. its connects and it does everthing
but it doesnt respond to commands
can anyone help me?
It's not a coroutine btw
thanks
also @mild geode you shouldn't store user levels in a json file
but when i do bot.command
i get error
Traceback (most recent call last):
File "C:\Users\user\OneDrive\Desktop\Coding\Nexus\main.py", line 64, in <module>
@client.command(name=level)
AttributeError: 'Client' object has no attribute 'command'
because you need to replace your client with a commands.bot
Only discord.ext.commands.Bot has command extension
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
you shouldn't mix on_message commands and commands extension together either
hmm
can anyone help me how do i do this?
i did the logic behind the code
but im not good at discord
so yeah. any help?
like instruct me plz
can u just give me an example command?
ill do the rest
@smoky sinew ```Microsoft Windows [Version 10.0.19045.2604]
(c) Microsoft Corporation. All rights reserved.
C:\Users\xavie\OneDrive\Documents>kca.py
File "C:\Users\xavie\OneDrive\Documents\kca.py", line 51
await bot.setup()
^^^^^^^^^^^^^^^^^
SyntaxError: 'await' outside function
C:\Users\xavie\OneDrive\Documents>```
im confused on this part.
The error literally just told you
would you mind giving me an example command?
are you trying to call setup_hook? it's called for you
just like hello world or smthing
yeah sure
thanks
@bot.command()
async def command(ctx):
await ctx.send("hello")
if you need a more complex example lmk
bro not the command like the whole code like the import and everything
cuz you told to do some commands.bot
i didnt get that part
ik this
from discord.ext import commands
isnt the issue with their original code that they didnt enable the message content intent?
thanks
Traceback (most recent call last):
File "C:\Users\user\OneDrive\Desktop\Coding\Nexus\main.py", line 3, in <module>
bot = commands.Bot(
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 171, in __init__
super().__init__(intents=intents, **options)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 1302, in __init__
super().__init__(*args, **kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 253, in __init__
self._connection: ConnectionState = self._get_state(intents=intents, **options)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 284, in _get_state
return ConnectionState(dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, http=self.http, **options)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\state.py", line 221, in __init__
raise TypeError(f'intents parameter must be Intent not {type(intents)!r}')
TypeError: intents parameter must be Intent not <class 'str'>
from discord.ext import commands
bot = commands.Bot(
command_prefix = "!",
intents = "intents"
)
@bot.event()
async def on_ready():
print(f"{bot.user} is online.")
@bot.command(name=hi)
async def hi(ctx):
await ctx.send('LETS GO!')
bot.run('Invalid')
you're meant to pass a discord.Intents object to the intents= parameter
and if you're planning to replace your on_message with commands.Bot + @bot.command(), you should follow the guide in the docs and perhaps see the github examples
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html
https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py
discord.Intents.all()
from discord.ext import commands
import discord
bot = commands.Bot(
command_prefix = "!",
intents = discord.Intents.all()
)
@bot.event()
async def on_ready():
print(f"{bot.user} is online.")
@bot.command(name=hi)
async def hi(ctx):
await ctx.send('LETS GO!')
bot.run('MTA3OTAxNTExNjc0MzM4NTE4OA.G3Kh-0.YHhMpo38q')
code
Traceback (most recent call last):
File "C:\Users\user\OneDrive\Desktop\Coding\Nexus\main.py", line 5, in <module>
intents = discord.Intents.all()
NameError: name 'discord' is not defined
C:\Users\user\OneDrive\Desktop\Coding\Nexus>python main.py
Traceback (most recent call last):
File "C:\Users\user\OneDrive\Desktop\Coding\Nexus\main.py", line 9, in <module>
@bot.event()
TypeError: event() missing 1 required positional argument: 'coro'
error
im rly sry
im just beginner in this discord.py.
ye kinda
ohk
what extra steps do i need to take to shard my bot?
i know i should use AutoShardedBot instead of Bot but is there anything else?
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.cog' raised an error: TypeError: cogs must derive from Cog
help!
anyone ?
meaning it must be a subclass of commands.Cog
does slash working? xD
That's a familiar pfp
i asking because i cant install slash dash module
class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
π€
I AM GETTING ERROR PLS FIX THIS Exception has occurred: TypeError BotBase.__init__() missing 1 required keyword-only argument: 'intents' File "C:\Users\badbo\Desktop\OwnedProjects\main.py", line 13, in <module> bot = commands.Bot(command_prefix='-',case_insensitive=True) TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'
Using intents in discord.py
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.
pip3 install discord-py-slash-command
its not needed?
!intents
No
Discord added slash commands on their new v2.0
I mean discord.py
Bro i am tripping π
!intent
Using intents in discord.py
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.
Oh NVM
!shashdash
-_-
root@sspanel:/home/bot# python3 bottesting.py
Traceback (most recent call last):
File "bottesting.py", line 2, in <module>
from discord_slash import SlashCommand, SlashContext
ModuleNotFoundError: No module named 'discord_slash'
Bro ππ
Use discord.py's official slash commands bruh
Dangggg
π
ai doesn't know the answer either
Don't say that it's chatgpt
Ash 
okay)
Ash on rescue
in my country go unblocked and i can use)
you me?
why my bot code is getting this output instead of logging into bot -_-
pls fix this
my bot code```import discord
from discord.ext import commands
import logging
from pathlib import Path
import json
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
cwd = Path(file).parents[0]
cwd = str(cwd)
print(f"{cwd}\n-----")
#bot secrets
secret_file = json.load(open(cwd+'/secrets.json'))
bot = commands.Bot(command_prefix="-",intents=intents, case_insensitive=True)
bot.config_token = secret_file['token']
logging.basicConfig(level=logging.INFO)
@bot.event
async def on_ready():
print(f"-----\nLogged in as : {bot.user.name} : {bot.user.id}\n-----\nMy current prefix is: -\n-----")
#another way to use activity
print("-----\nLogged in as: {} : {}\n-----\nMy current prefix is: -\n-----".format(bot.user.name, bot.user.id))
await bot.change_presence(activity=discord.Game(name=f"Hi, my names {bot.user.name}.\nUse - to insteract with me!"))
#bot activity
@bot.command(name='hi', aliases=['hello'])
async def _hi(ctx):
"""
A simple command which says hi to the author
"""
await ctx.send(f"Hi {ctx.author.mention}!")
#edit command
@bot.command()
async def echo(ctx, *, message=None):
"""
A Simple command that repeats the users input back to them
"""
message = message or "please provide the message to be repeated"
await ctx.message.delete()
await ctx.send(message)
bot.run(bot.config_token) ```
i am newbie so i dont know much about discord.py
the bot.run is inside a command?
umm yes
why
@vocal snowthnks buddy i got my fix
that was a silly mistake 
https://pastebin.com/FteajMjb bot dont sends welcome msg and leave
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
how do i make a slash command admin only?
what is this?
anybody help pls)
Looking now. Give me a sec
that didnt answer my question??
what statement and or code do i need to make a command admin only?
its easy system for perms in discord you can add for role and dont add to code
@glass forge Its just not sending the welcome and leave embed?
yes
what you can say?
I'm running it rn on my server. Ill give you an answer in a sec
m?
!d discord.app_commands.checks.has_permissions
@discord.app_commands.checks.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the permissions given by [`discord.Interaction.permissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.permissions "discord.Interaction.permissions").
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingPermissions "discord.app_commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0...
Probably this
Not probably, it is
its not for me
Code?
this
I'm not sure if it applies restrictions on client end
for me
Mhm
.
Ohh this!!
try setup welcome and quit msg
Sorry nvm
Sorry I am bad at reading
ha
!d discord.app_commands.default_permissions
@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.
When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.
Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.
This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check"). Therefore, error handlers are not called.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
@glass forge this ^^^
Oh wait, my bad lol
π€£ sorry
Members intent required + does client even have those methods?
async def on_member_join(self, member):
guild = self.get_guild(796804050305417276) # Replace with your guild ID
channel = guild.get_channel(1079697563848028180) # Replace with your channel ID
# Create a welcome embed with a mention of the new member
embed = discord.Embed(title=f"Welcome {member.mention}!", description="Hello and welcome to our server!")
await channel.send(embed=embed)
async def on_member_remove(member):
guild = self.get_guild(796804050305417276) # Replace with your guild ID
channel = guild.get_channel(1079697563848028180) # Replace with your channel ID
# Create a goodbye embed with a mention to the leaving member
embed = discord.Embed(title="Goodbye!", description=f"{member.mention} has left the server. Bye!")
await channel.send(embed=embed)
!d discord.Intents.default
classmethod default()```
A factory method that creates a [`Intents`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents "discord.Intents") with everything enabled except [`presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences "discord.Intents.presences"), [`members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members"), and [`message_content`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.message_content "discord.Intents.message_content").
its where?
Using intents in discord.py
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.
if i dont want use command_prefix and want use /
Same
!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 "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 "discord.Client").
New in version 1.5.
all my code
read again
In
super().init(....)
Change to this ^^^^
intents=discord.Intents.all()
discord dont ban?
@bot.slash_command()
async def where(inter, *, id):
channel = bot.get_channel(1076863262613835828)
messages = await channel.history().flatten()
for index, element in enumerate(messages):
print(index, element.reactions[index])
async for user in element.reactions[index].users():
if bot.get_user(id) == user:
u = bot.get_user(id)
inter.response.send_message(f"{u.name} is from {element.reactions[index].emoji}")
break
using disnake
this hella confuses me, how do i get what the user reacted with in any message of a channel
File "bottesting.py", line 2
class discord.Intents.all()
^
SyntaxError: invalid syntax```
Bruhhh
Did u try checking your own code?
There is a
super().init(...)
yes)
Search it and lmk o
If u found it
Fu##
?
work
Realized? xd
π€£
lol
how remove prefix
Hello guys, I am using cogs. How do I sync my commands??
u cant
Just remove the line easy
!d discord.ext.commands.Bot.add_cog
await add_cog(cog, /, *, override=False, guild=..., guilds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a βcogβ to the bot.
A cog is a class that has its own event listeners and commands.
If the cog is a [`app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") then it is added to the botβs [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") as well.
Note
Exceptions raised inside a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog")βs [`cog_load()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.cog_load "discord.ext.commands.Cog.cog_load") method will be propagated to the caller...
slash commands it is
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
Show code?
its not work
What
how do i get what the user reacted with in any message of a channel
trying to sync this command but its not syncing... https://paste.pythondiscord.com/edelicokaf
my brain is expldoing
Sync it on setup_hook event
Or just on start
@bot.event
async def on_ready():
bot.loop.create_task(change_status())
print("Bot is online!")```
in the main() function?
on_ready works too but bad use setup_hook
Dont do it, I realized u r using extensiona
yes
Extensions,
So better sync it on setup_hook
@bot.event
async def setup_hook()
await bot.tree.sync()
print("Yeah i synced commands and triggered setup_hook")
πππ
π§
where tf all the commands went
async def main():
for filename in os.listdir('./commands'):
if filename.endswith('.py'):
await bot.load_extension(f'commands.{filename[:-3]}')
await bot.start("Bottoken")
discord.utils.setup_logging()
#setup hook
@bot.event
async def setup_hook():
await bot.tree.sync()
print("Synced all the commands!")
keep_alive()
asyncio.run(main())```
Wait, remove setup_hook then, add other codes on main() function
Wait f it's so weird
Can u show ur main.py code?
Try syncing on on_ready event
works nothing
my commands are vanished
you cant mention in title
move it to description
a yes? sorry
try this... synced=await bot.tree.sync()
print(synced)
Maybe the bot doesn't have perms? Who knows
Administrator crying in the corner
with bot applications enabled
I can see only one command
Hm 
.
app.commands scope enabled?
Bro why loop lmao
its only syncing one command
Maybe u have only 1 slash cmd? π
who help me, very thanks
Nice
sure
how get budget?))
I am using
BRO ITS RANDOMLY SYNCING COMMANDS
it now synced help cmd
only help cmd now
ππππππ
Wait π
Ig try
to sync it on setup
Deb portal, search on google, u will get the link eventually
done yet π
Rip π
what
Nothing
U canβt mention anything on embed title
already solved lol
Oh lol
----------______________________--------------
pls anyone?
Have your own discord bot that supports slash commands in a community server (also have atleast 1 of the commands used in last month (iirc))
@bot.command()
async def google(ctx,arg):
var_content = []
var_header = []
# Searching Google For Top Links
var_searchQuery = str(arg)
var_results = search(var_searchQuery , tld = "co.in" ,num = 3 ,stop = 3 , pause = 2)
var_links = []
for result in var_results :
var_links.append(result)
else :
print("links found")
# Fetching Data from Websites
for link in var_links :
var_rawData = req.get(link)
var_htmlData = var_rawData.content
var_soup = bs(var_htmlData , "html.parser")
var_tempHeader = var_soup.find("title")
var_tempContent = var_soup.find("p")
var_content = var_content.append(var_tempContent.text)
var_header = var_header.append(var_tempHeader.text)
await ctx.send("Fetching Results...")
else:
print("started making embed")
var_resultsEmbed = discord.Embed(title = f"Search Results For `{arg}`", color = 0x00ff00,
url= "https://google.com")
var_resultsEmbed.add_field(name=f"{var_header[0]}",value=f"{var_content[0]}",inline = False)
var_resultsEmbed.add_field(name=f"{var_header[1]}",value=f"{var_content[1]}",inline = False)
var_resultsEmbed.add_field(name=f"{var_header[2]}",value=f"{var_content[2]}",inline = False)
await ctx.send(embed=var_resultsEmbed)
any idea why is this not working
no errors
it just stops after one iteration
the for loop
why are you doing var_content = var_content.append()?
append doesnt return, it adds inplace. You just need var_content.append()
it's to make the list of all the results
@lyric sphinx :white_check_mark: Your 3.11 eval job has completed with return code 0.
None
!e
x = []
x.append(10)
print(x)
@lyric sphinx :white_check_mark: Your 3.11 eval job has completed with return code 0.
[10]
also whats the point of naming every variable var_<name> lmao
Why else: is after for loop statement?
don't judge me but idk i find it cool πββοΈ
Its valid
loop else
[2023-02-27 18:04:04] [WARNING ] discord.gateway: Shard ID None heartbeat blocked for more than 10 seconds.
Loop thread traceback (most recent call last):
Oh wait nvm
!blocking
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
yes
like just replce requests rest of the things like b4s will be same right ?
Just,
async with aiohttp.ClientSession() as ses:
var_rawData=await ses.get("url")
what bot

!rule paid
L
how do I make the subcommands work
Slash sub cmds?
the slash commands are finally synced but the slash sub cmds are not syncing in any way
is there any problem with my slash cmds?
.
Maybe ur sub cmds are wrong?
Sec
It isnt a sub command?
Mind searching in google "discord.py app_commands walk through" there is all types.of slash commands with cog and without cog
wdym
It doesnt even have anything related to sub commands in your code
thats just a slash command
how do I make it a subcommand
how do I make a parent cmd
subcommand of what?
"search"
Please, ik it's against rule to answer people with only telling google
I cant search rn, that's why gave u
Oh f, need to check docs
Docs*, there is something similar to this
docs earlier was π
!d discord.app_commands.Group
class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., nsfw=..., auto_locale_strings=True, default_permissions=..., extras=...)```
A class that implements an application command group.
These are usually inherited rather than created manually.
Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only"), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds "discord.app_commands.guilds"), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions "discord.app_commands.default_permissions") will apply to the group if used on top of a subclass. For example:
```py
from discord import app_commands
@app_commands.guild_only()
class MyGroup(app_commands.Group):
pass
```...
hellow, does anyone is currently developping a bot with python 3.11.2 and VScode ?
apgg
!d discord.ext.commands.Bot.hybrid_group
U found it xd
@hybrid_group(name=..., with_app_command=True, *args, **kwargs)```
A shortcut decorator that invokes [`hybrid_group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.hybrid_group "discord.ext.commands.hybrid_group") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.add_command "discord.ext.commands.Bot.add_command").
Not hybrid ππ
iirc dpy doesn't officially support 3.11 yet (it should still work though)
is that why im swiming in the void to set it up, i guess soπΏ
Lol
Are you getting an error?
what version do you recommand to me
3.10
^
yeah i tried everything
Python version
Tho python 3.11 wont give much problems
dpy is pure python, so it should work just fine in 3.11 anyway
so my error doesn't come from the py version
Are you getting 'missing required argument intents'?
dpy supports python 3.11, aiohttp was missing wheels for that version
Ah ic, good to know
i deleted everything to do it properly with yall advices x)
wasn't able to start a thing anyway
hi uh
@bot.command()
async def google(ctx,arg):
var_content = []
var_header = []
# Searching Google For Top Links
var_searchQuery = str(arg)
var_results = search(var_searchQuery , tld = "co.in" ,num = 3 ,stop = 3 , pause = 2)
var_links = []
for result in var_results :
var_links.append(result)
else :
print("links found")
# Fetching Data from Websites
for link in var_links :
async with aiohttp.ClientSession() as ses:
var_rawData=await ses.get(link)
var_htmlData = var_rawData.content
var_soup = bs(var_htmlData , "html.parser")
var_tempHeader = var_soup.find("title")
var_tempContent = var_soup.find("p")
var_content.append(var_tempContent.text)
var_header.append(var_tempHeader.text)
await ctx.send("Fetching Results...")
else:
print("started making embed")
var_resultsEmbed = discord.Embed(title = f"Search Results For `{arg}`", color = 0x00ff00,
url= "https://google.com")
var_resultsEmbed.add_field(name=f"{var_header[0]}",value=f"{var_content[0]}",inline = False)
var_resultsEmbed.add_field(name=f"{var_header[1]}",value=f"{var_content[1]}",inline = False)
var_resultsEmbed.add_field(name=f"{var_header[2]}",value=f"{var_content[2]}",inline = False)
await ctx.send(embed=var_resultsEmbed)
still not working
like idk if the loop is even iterating
it didn't send even one response
@lyric sphinx
it's not fetching data
i checked
Hey @mild geode!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
I made this. But everytime I rerun the code the balance gets reset. I want to store all users and their balance in a txt file. So that we can read and write everytime they earn or lose something.
Anybody can help me here?
you really shouldnt use a plaintext for this
thats a great opportunity to learn databases :d
hmm
which one do you suggest? although i just want in plain text tbh
SQLite is probally the easiest to use
what about mine 
how about i try making it as an external function and just call that function in the bot command
shouldnt it be something like
async with session.get("link") as r:
will it work 
cuz when i was doing this outside of the bot code
it just worked
it worked good there
well, because it didnt have to do any async stuff
the actual code was fine for a standalone command, but not for a bot
so it will be the same even if i make it as an external function
and call it under the async
does anyone have a clue about that ?
What are you trying to do
i'm following a tutorial to get discord.py
yeah sadly i'm not getting nice stackoverflow resources
yeah pip work outside python
but why does it work inside for him uhh
It's meant to be use in the terminal/console/whatever
yeah
i think thats the onboarding community feature
ohhhh
when should I change presence?
So question, how does a bot like Mee6 handle being in like 20+million servers?
Can someone give me reasons why not to use replit? Everyone has told me that it sucks but I can't see why lol. If you can suggest some other code editor that's free and can run in the browser then great but right now I don't see replit as being an issue.
use vscode?
oh
yeah my issue is i cant install software on pc bcs i dont own the pc
there's an explanation on its caveats in the pythondiscord site
https://www.pythondiscord.com/pages/guides/python-guides/vps-services/#why-not-to-use-free-hosting-services-for-bots
This article lists recommended VPS services and covers the disasdvantages of utilising a free hosting service to run a discord bot.
Hi I watched a video on how to make a discord bot but when I run it it just says this
`Traceback (most recent call last):
File "E:\PyCharm Projects\Teki-Key Bot\main.py", line 4, in <module>
bot.run_discord_bot()
File "E:\PyCharm Projects\Teki-Key Bot\bot.py", line 15, in run_discord_bot
client = discord.Client()
TypeError: Client.init() missing 1 required keyword-only argument: 'intents'
Process finished with exit code 1`
!intents
Using intents in discord.py
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.
the tutorial you're watching is likely outdated by now since discord.py 2.0 got released six months ago
if it has to be the same throughout the session you can do it using status and activity kwarg inside the bot constructor, else you can do it anywhere after the bot is connected to websocket and all the READY and initial GUILD_CREATE events have been processed ( which discord.py looks after with the Client.wait_until_ready() lock
see the tag:
Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
and the code snippet inside demonstrates how you would define your intents and pass it as an argument to your bot constructor
I'm new still so im really stuck
you sound like me when i started lol
Lol
!e py def my_function(*, intents): ... this is a function, and in this case the parameter intents is 1: required, and 2: keyword-only, so when you call the function it must be done like this: py my_function(intents="hello world!") if you don't pass said argument and just call the function without any arguments: py my_function() you get the same error you saw before:
@hushed galleon :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | TypeError: my_function() missing 1 required keyword-only argument: 'intents'
the prior tag explains why intents matter to your discord bot, how to enable privileged intents in the discord developer portal like message_content, and how to specify the intents you want your bot to use when its connecting to discord
i also suggest reading the documentation's quickstart and some of the examples on discord.py's github page since those are up-to-date resources
https://discordpy.readthedocs.io/en/stable/quickstart.html
https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py
class NewWarnModal(nc.ui.Modal):
def __init__(self, target):
self.target = target
super().__init__(f"Warning for {self.target}")
self.reason = nc.ui.TextInput(label="Reason", style=nc.TextInputStyle.paragraph, placeholder="Type here your reason", required=True, max_length=50)
self.add_item(self.reason)
async def callback(self, inter: nc.Interaction):
async with aiosqlite.connect("maja.db") as db:
async with db.cursor() as cursor:
random_id = generate_random_id(10)
user_dm = nc.Embed(title=f"You are beeing warned on {inter.guild.name}",
description=f"__**Reason:**__\n{self.reason}")
user_dm.set_footer(text=f"Warned by: {inter.user}", icon_url=inter.user.avatar.url)
current_time = int(time.time())
await cursor.execute('INSERT INTO warn_system (guild_id, user_id, warned_by, date, reason, case_id) VALUES (?, ?, ?, ?, ?, ?)',
(inter.guild.id, self.target.id, inter.user.id, current_time, self.reason.value, random_id,))
await inter.response.send_message(content="sucess")```
The Insert wont work
No error
He sends sucess
it doesnt look like you committed your transaction
!intent
Using intents in discord.py
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.
Where do I put that
put it on your bot instance
If u using class
put it inside ....
super().init(....)
@vocal wraith the first part of the quickstart is what you need
In bot.py I assume?
i need someone to help me. i havent coded in months and i may have forgotten a lot and ik stuff is outdated lmao
wherever you wrote discord.Client()
I have bot.py, responses.py, and main.py, I got this all of yt vid lol
depends on how they named their script
its outdated now
make sure that youre watching an up to date tutorial
@hushed galleon can you help me rewrite in dms
True thanks
Can someone make me a bot for my server?
depends... what do u want it to do
The stuff mee6 can do but I don't like mee6 cuz of all the trouble that is going on with it
uh yeah i cant do that much sry, try bots like dyno tbh
dm me i can help
Ok
interaction.client.get_channel
client?
!d discord.Interaction.client 
property client```
The client that is handling this interaction.
Note that [`AutoShardedClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoShardedClient "discord.AutoShardedClient"), [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot"), and [`AutoShardedBot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.AutoShardedBot "discord.ext.commands.AutoShardedBot") are all subclasses of client.
await self.bot.unload_extension(. . .) to unload another cog from a cog
Given a string S check if is a valid email id based on the following Conditions
1)@ should be present;
2)@ & . should not be repeated;
3)there should be atleast four characters between @ and .;
4)there should be at-least 3 characters before @ ;
5)the end of mail id should be .com; If its a valid email id print 'YES' else print 'NO'.
input size : |S|<=100000
example
INPUT
test@gmail.com
OUTPUT
YES
need help
email_re = re.compile(r'^[a-z_-]{3}+@[a-z]{3}+.[a-z]{3}$')
user_email_id = input("enter your id π
if re.search(email_re, user_email_id):
print("right email")
else:
print("invalid email")
code i have written showing incorrect
class SelectEditWarn(nc.ui.Select):
def __init__(self, target):
self.target = target
async def get_options(self):
async with aiosqlite.connect("maja.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT case_id FROM warning_system WHERE user_id, guild_id = ?, ?', (self.target.id, nc.Interaction.guild.id,))
case = await cursor.fetchall()
return case
for option in get_options:
async def get_reason(self):
async with aiosqlite.connect("maja.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT reason FROM warning_system WHERE case_id, guild_id = ?, ?', (option, nc.Interaction.guild.id,))
reason = await cursor.fetchone()
new_option = nc.SelectOption(label=option, description=reason[0])
super().__init__(placeholder="Choose a chase", min_values=1, max_values=1, options=#I can't get any further here)```
The idea is to get all warnings from the member and then list them in a select menu so you can look for a case
await interaction.client.load_extension(. . .)
``` would work?
For me?
no
Mb I forgot to reply
Btw how do I get the reason for ban in on_member_ban event?
import asyncio
from random import random
from re import M
from secrets import randbelow
from urllib import response
from click import CommandCollection
import discord
from discord.ext import commands, tasks
from itertools import cycle
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
client = commands.Bot(command_prefix='=', intents=intents)
bot_status = cycle(["Watchig everyone", "Moderating", "banning a person"])
@tasks.loop(seconds=10)
async def change_status():
await client.change_presence(activity=discord.Game(next(bot_status)))
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
@client.event
async def on_ready():
print(f'Logged in as {client.user} (ID: {client.user.id})')
print("Success: The bot is connected to discord")
change_status.start()
#commands list
@client.command()
async def hello(ctx):
await ctx.send("Hi. How's going ? It's good to here from you.")
@client.command()
async def ping(ctx):
await ctx.author.send("Pong!")
async def load():
for filename in os.listdir("discrdbot\cogs"):
if filename.endswith(".py"):
await client.load_extension(f"cogs.{filename[:-3]}")
print(f"{filename[:-3]} is loaded!")
async def main():
async with client:
await load()
await client.start("MY BOT TOKEN")
asyncio.run(main())```
the main code
from discord.ext import commands
class cogs(commands.Bot):
def __init__(self, client):
self.client = client
class Greetings(commands.Cog):
def __init__(self, client):
self.client = client
self._last_member = None
@commands.Cog.listener()
async def on_member_join(self, member):
channel = member.guild.system_channel
if channel is not None:
await channel.send(f'Welcome {member.mention}.')
@commands.command()
async def hello(self, ctx, *, member: discord.Member = None):
"""Says hello"""
member = member or ctx.author
if self._last_member is None or self._last_member.id != member.id:
await ctx.send(f'Hello {member.name}~')
else:
await ctx.send(f'Hello {member.name}... This feels familiar.')
self._last_member = member
def setup(bot):
bot.add_cog(cogs(bot))
@commands.Cog.listener()
async def on_ready(self):
print("cogs.py is ready!")
@commands.command()
async def embed(self, ctx):
embed_message = discord.Embed(title="Title of embed", discription="Discription of embed", colour=discord.Colour.orange)
embed_message.set_author(name=f"Request by {ctx.author.mention}", icon_url=ctx.author.avatar)
embed_message.set_thumbnail(ul=ctx.guild.icon)
embed_message.set_image(url=ctx.guild.icon)
embed_message.add_field(name="Field name", value="Feild value", inline=False)
embed_message.set_footer(text="This is the footer", icon_url=ctx.author.avatar)
await ctx.send(embed = embed_message)
async def setup(client):
await client.add_cog(cogs(client))```
the cog
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.ping' raised an error: TypeError: cogs must derive from Cog```
the error
what's the problem ?
the tutorial u are following
What
extensions dont typically need to define a subclass of commands.Bot
can you help me remake discord bot
in your case you probably meant to construct an instance of the Greetings cog
Can you write me a discord bot code ? π
I'm saying that bro
ohk
i would still suggest reading the resources i linked and try to rewrite your bot with what you learn, and ask here when you're stuck
intents: https://discordpy.readthedocs.io/en/stable/intents.html
example bot: https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py
guide for writing commands: https://discordpy.readthedocs.io/en/stable/ext/commands/index.html
Okay cheers
What happened to your bot?
he doesnt know how to code, and needs someone to walk him through it. the tutorial he tried was outdated
Bro that's happening with me too
But the tutorial is 5 months old
And still giving me errors
Discord.py changes very frequently, especially the past few months. I wouldn't recommend any tutorial a month or 2 old
Heck, I don't recommend tutorials for discord.py in general
Why
Simply put the vast majority of them are either A) outdated or B) terrible
Pardon?
Yep
... I- I'm not following
π
Can someone make me a bot like sounds?
no
i think he wants you to give him a "terrible" tutorial since he doesnt want an "outdated" one π
yk whats crazy tho, i have a discord bot running in one of my servers and i havent touched its code in months up to a year, and it has no issues somehow
Traceback (most recent call last):
File "main.py", line 4, in <module>
from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType
ModuleNotFoundError: No module named 'discord_components'
ξΊ§
can somebody help me out with this?
try updating the libraries
or wait a little longer for discord to deprecate that api version 
use discord.py not third party libs
im try create custome voice
async def on_voice_state_update(member, before, after):
if before.channel is None and after.channel is not None and after.channel.id == 1070962969904680970: # Replace with the ID of the source voice channel
# Get the target voice channel by ID
target_channel = bot.get_channel(1079874258668367933) # Replace with the ID of the target voice channel
# Create a new custom voice channel with a unique name
new_channel = await target_channel.category.create_voice_channel(name=f"Custom Voice Channel - {member.display_name}")
# Move the member to the new channel and give them permissions to edit the channel
await member.move_to(new_channel, reason="Moved to a custom voice channel", permissions=discord.Permissions(voice=True, manage_channels=True))
``` its correct?
async def clear(ctx, limit: int = None):
with open("access.txt") as f:
if str(ctx.guild.id) not in f.read():
if limit == None:
await ctx.channel.purge(limit=30)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
else:
if limit > 30:
await ctx.send("[**ERROR**] Your max limit is 30.")
else:
await ctx.channel.purge(limit=limit)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
elif str(ctx.guild.id) in f.read():
if limit == None:
await ctx.channel.purge(limit=10000)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")
else:
await ctx.channel.purge(limit=limit)
await ctx.send("[ **SUCCESSFULLY** ] - *deleted messages*")```
why it didnt work?
Could you mind elaborating a bit more? I'm not sure I'm following what you mean by "field"
.
whats wrong with it
Ah, I see what you mean. The before and after objects of certain events gives you the entire new state of the objects, rather than just the incremental changes
It's up to you to parse out which is new and which is old information, unfortunately
Well.. an embed "field" can have one title and one value
When you look at it that way, it does make sense why you can't "append" to a value
That would imply you can have more than one value
(which you don't)
Bot don't create voice
I'm guessing by "adding values to an embed field" you mean adding a new "line" seperated by \n
Which is still just "one value"
I hope that perspective explains why you can't "append to a value"
... However it does have a pretty simple "fix"
You'd create some variable that stores the value of the field, append to the variable, then you'd update the embed and pass in the variable as the value
So:
my_var = "This is line 1"
my_embed = discord.Embed(...)
my_embed.add_field(..., value=my_var)
# you can now "update" the field:
my_var += "\nThis is line 2!"
# Edit the view, resend it
The idea is to not directly edit the Embed, but to edit it via a "proxy" of sorts, if that makes sense
do you have the members intent??
@glass forge
anyone know what property is used to check the invite the user joined from
or is it just detected by seeing which invite goes up in uses when someone joins?
yep the discord API doesn't provide any way to figure that out explicitly
you'll have to see the invite logs
wdym?
how do I check the interaction user's permission? got it
Compare the invite logs before and after, check for the delta
discord.ext.commands.errors.MissingRequiredArgument: guess is a required argument that is missing
what to do ?
Give it enough arguments
I don't know about coding that's why I'm asking bro tell me what to do
step 1: you dont copy code which u don't understand
what do you mean by invite logs
what delta??
it's in the error
read what it says
okπ
Basically all the invites your server has and how many people have used it
You know which invite was used by figuring out which count went up by 1
It's frankly a major PITA
yeah that's what i suggested
i want to create a lobste.rs type invite tree command
How do I set a description for an argument?
!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...
thank you
||also if anyone has a lobste.rs account and can invite me that would be very cool||
how do I add the mention thing in the argument
?
the ban command
thanks
async def hello(ctx):
with open("discrdbot/random.txt", "r") as f:
random_responses = f.readlines()
response = random.choice(random_responses)
await ctx.send(response)```
'choice'```
How do I send the direct message to the user when the user is banned?
help me ! tell me what to do
Just send it? π€· what's the problem
!d discord.Member.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
What is random
π
good question
tell be bro, I don't want that my bot giving me the same greetings all the time
i would hope random is the builtin random module
Can u show what is random
How am I supposed to help if I don't even how what that thing is
here
..
let me check
sure
send it before they get banned
I just read the docs but still did the same
π
Do some checks that user can be banned or not like comparing role , position etc then send then ban
can you send the full traceback instead
yes
and possibly your full code

is there a afk json database code?
you can post it here if it's a large file
https://paste.pythondiscord.com/
JSON isn't a database
check bro
We dont provide full code here
oh
Its not full
where do i find em
ok i'm sending
Nice
where do i find full codes
Create ur own go check json docs
?
this shouldn't matter btw since its a text file and not a python file
from random import random, choice
from re import M
from secrets import randbelow
from urllib import response
from click import CommandCollection
import discord
from discord.ext import commands, tasks
from itertools import cycle
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='=', intents=intents)
bot_status = cycle(["Watchig everyone", "Moderating", "banning a person"])
@tasks.loop(seconds=10)
async def change_status():
await bot.change_presence(activity=discord.Game(next(bot_status)))
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
@bot.event
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
print("Success: The bot is connected to discord")
change_status.start()
#commands list
@bot.command()
async def ping(ctx):
await ctx.send("Check your Dms'.")
await ctx.author.send("Pong!")
@bot.command()
async def hello(ctx):
with open("discrdbot/responses.txt", "r") as f:
random_responses = f.readlines()
response = random.choice(random_responses)
await ctx.send(response)
bot.run("bot token")```
um , yeah
Now good
hmm
why are you import random from random
Bruh
you should be using choice directly since you imported that from random
and not importing random from random either
I didn't do it it's automatic
wdym
ok
Using vsc right?
yes
Yeah got it
either way, its wrong
its also not recommended to use on_ready for anything that can make an API requests, along with using urllib since its blocking πΊ
It auto add import code when u try to use a module in code
That u didnβt imported
then what should I use ?
should I use from random import choice ?
!e
import random
print(random.choice(range(10)))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
9
Just import it normally π€¨
ok
i think you can use the setup hook here (granted you're using discord.py, otherwise idk)
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.setup_hook
let me check
and you're going to copy and paste more things
good luck with that
yeah and you said you copied and pasted all of it from tutorials
Great!
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range now it's giving me this
Error says all
The index ur trying to access isnt there
I think it added from urllib import response just because they have a line in a function that starts with response =
what ?
could be some vsc fuckery going on, i disable auto imports though
Meaning @frosty parrot should remove that meaningless import line
!e
a = [1,2]
print(a[2])
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | IndexError: list index out of range
@bot.tree.command(name="equip")
@app_commands.describe(tests="test")
@app_commands.choices(choices=[
app_commands.Choice(name="country", value="country"),
app_commands.Choice(name="planet", value="planet"),
])
async def rps(i: discord.Interaction, choices: app_commands.Choice[str], tests:str):
if (choices.value == "country"):
Whatever[i.user.id] = "country"
elif (choices.value == 'planet'):
Whatever[i.user.id] = "planet"
@rps.autocomplete("tests")
async def choice(ctx,choice:str):
d = []
if Whatever[ctx.user.id] == "country":
for c in ["country1","test2","test3",
"test4","test5","test6"
]:
if choice.lower() in c.lower():
d.append(app_commands.Choice(name=c, value=c))
if Whatever[ctx.user.id] == "planet":
for c in ["planet","test2","test3",
"test4","test5","test6"
]:
if choice.lower() in c.lower():
d.append(app_commands.Choice(name=c, value=c))
return d
is the text file empty
Only if people actually read the errors
obviously not
what specifically are you referring to
choices are handled for you i'm pretty sure but you need to annotate it as Choice
By the way why are you setting an event loop policy
For it to work properly on Windows
oh I forgot to delete that I was using another code thats why
Can you paste your code now so I know why you got that last error?
π€·
are you asking me ?
Yes
wait for a little while I'm sending my full code
User entered the first value of choice, and second choice's value will be change according to the first value
Same here
import random
print(random.choice(range(10)))
from re import M
from secrets import randbelow
from urllib import response
from click import CommandCollection
import discord
from discord.ext import commands, tasks
from itertools import cycle
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='=', intents=intents)
bot_status = cycle(["Watchig everyone", "Clash of Clans",])
@tasks.loop(seconds=10)
async def change_status():
await bot.change_presence(activity=discord.Game(next(bot_status)))
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
@bot.event
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
print("Success: The bot is connected to discord")
change_status.start()```
async def ping(ctx):
await ctx.send("Check your Dms'.")
await ctx.author.send("Pong!")
@bot.command()
async def hello(ctx):
with open("discrdbot/responses.txt", "r") as f:
random_responses = f.readlines()
response = random.choice(random_responses)
await ctx.send(response)
class Greetings(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.Cog.listener()
async def on_member_join(self, member):
channel = member.guild.system_channel
if channel is not None:
await channel.send(f'Welcome {member.mention}.')
@commands.command()
async def hello(self, ctx, *, member: discord.Member = None):
"""Says hello"""
member = member or ctx.author
if self._last_member is None or self._last_member.id != member.id:
await ctx.send(f'Hello {member.name}~')
else:
await ctx.send(f'Hello {member.name}... This feels familiar.')
self._last_member = member```
It might also be a good idea to open the text file only once before running the bot so opening the text file doesn't block for too long when the bot is running and the library's gateway should be responsive. That or you can use aiofiles (a package on PyPi) which provides an asynchronous interface similar to the one in Python
async def embed(self, ctx):
embed_message = discord.Embed(title="Title of embed", discription="Discription of embed", colour=discord.Colour.orange)
embed_message.set_author(name=f"Request by {ctx.author.mention}", icon_url=ctx.author.avatar)
embed_message.set_thumbnail(ul=ctx.guild.icon)
embed_message.set_image(url=ctx.guild.icon)
embed_message.add_field(name="Field name", value="Feild value", inline=False)
embed_message.set_footer(text="This is the footer", icon_url=ctx.author.avatar)
await ctx.send(embed = embed_message)
@bot.command()
async def userinfo(ctx, member: discord.Member=None):
if member is None:
member = ctx.author
elif member is not None:
member = member
info_embed = discord.Embed(title=f"{member.name}'s User Information", discription="All information about this user.", color=member.color)
info_embed.set_thumbnail(url=member.avatar)
info_embed.add_field(name="Name", value=member.name, inline=False)
info_embed.add_field(name="Nick Name", value=member.display_name, inline=False)
info_embed.add_field(name="Discriminator", value=member.discriminator, inline=False)
info_embed.add_field(name="ID", value=member.id, inline=False)
info_embed.add_field(name="Top Role", value=member.top_role, inline=False)
info_embed.add_field(name="Status", value=member.status, inline=False)
info_embed.add_field(name="Bot User", value=member.bot, inline=False)
info_embed.add_field(name="Creation Date", value=member.created_at.__format__("%A, %d. %B %Y @ %H:%M:%S"), inline=False)
await ctx.send(embed=info_embed)
bot.run("bot token")```
main file
Hello
How are you doing
How can I help you```responses.txt
I actually don't know coding, I'm following a tutorial
just tell me what to do or I cant understand
π
I can see points of improvement
But I don't see anything that would raise an IndexError
Are you still getting it?
Can you locate the line
but normally it's working
In the error traceback
yea wait
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range
Alright but what line does it say that it did that?
What line of code does the error traceback says raised the exception
What's the above exception? It says
The above exception was the direct cause of the following exception:
then what to do now ?
You can send the entire traceback you're getting as a text file or something
!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 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.
Send the full traceback in this
Ye
Can you also send the full error message?
oh shit no
We need to see it to know what's going wrong π
f.readlines() must be returning an empty list
random.choice raises that exception on an empty collection, I've just tested
Hello
How are you doing
How can I help you```
this is the responses.txt file
Where does discordbot (the folder) sit relatively to this file
Frankly I think you would get an OSError for trying to open a non existent path in reading mode, so the path should be accessible to the script
Have you tried saving responses.txt
if I don't use the responses.txt then ?
It was probably empty before you edited it and forgot to save
And your Greetings cog won't load itself. Also it has its own hello command which would conflict with the cogless hello command we're working on
really ?
then I have to delete the command right ? or change the greetings ?
!d discord.ext.commands.Bot.add_cog
await add_cog(cog, /, *, override=False, guild=..., guilds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a βcogβ to the bot.
A cog is a class that has its own event listeners and commands.
If the cog is a [`app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") then it is added to the botβs [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") as well.
Note
Exceptions raised inside a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog")βs [`cog_load()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.cog_load "discord.ext.commands.Cog.cog_load") method will be propagated to the caller...
Normally you'd have something like this in your setup_hook override:
async def setup_hook(self):
# for every cog
self.add_cog(Cog(self))
add_cog is a coroutine, so await it
Or even better, put each cog in its own file as an extension and load the extension in setup_hook. Make sure the setup function in the extension files calls add_cog and stuff
I didn't understand that cause I don't know about it
my ping.py isn't loading so I didn't load that
I have more commands in that file
And also it isn't saved
π
bro you are right π
it wasn't saved π€
If it's loaded, sure. It shouldn't conflict then
hi
How would I setup my discordbot so it detects whenever it joins a new discord server?
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
No problem
Can I make my discordbot automatically leave a server as well?
Leave when
!d discord.Guild.leave
await leave()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Leaves the guild.
Note
You cannot leave the guild that you own, you must delete it instead via [`delete()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.delete "discord.Guild.delete").
now what is it ?cycle expected 1 argument, got 2
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
@tasks.loop(seconds=10)
async def change_status():
await bot.change_presence(activity=discord.Game(next(bot_status)))```
!d itertools.cycle
itertools.cycle(iterable)```
Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. Roughly equivalent to:
```py
def cycle(iterable):
# cycle('ABCD') --> A B C D A B C D A B C D ...
saved = []
for element in iterable:
yield element
saved.append(element)
while saved:
for element in saved:
yield element
```...
Needs to be in a list or something
but it was working fine
And it now is?
yes
oh the third brackets ? [] ?
The brackets on line eighteen here
They are the one and only pair of brackets on that line
oh
I removed them I thought it's useless
oh it's working now
The pair of brackets makes it a list (which itertools.cycle accepts). Without the brackets you would be sending it multiple arguments which itetools.cycle doesn't accept. The trailing comma before the closing bracket is useless
yes
oh ok
can you teach me python after 1 month ?π
I have exams from march 14. so after that I'll start learning python
Good luck
thanks
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Embed.__init__() got an unexpected keyword argument 'discription'
what is it ?
I used userinfo command
description not discription
shit
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
this one ?
Hey @spice zenith!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Traceback (most recent call last):
File "C:\Users\jaime\PycharmProjects\BOT\venv\lib\site-packages\discord\app_commands\commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "C:\Users\jaime\PycharmProjects\BOT\EX BOT\main.py", line 1595, in shop
d.execute("""
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\jaime\PycharmProjects\BOT\venv\lib\site-packages\discord\app_commands\tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\jaime\PycharmProjects\BOT\venv\lib\site-packages\discord\app_commands\commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\jaime\PycharmProjects\BOT\venv\lib\site-packages\discord\app_commands\commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'shop' raised an exception: InterfaceError: Error binding parameter 1 - probably unsupported type.
im getting this error in that code and idk why^^'
can anyone help me pls
have there been any updates to discord in terms of components? anything new aside from selects, buttons and the pop out forms
i would guess one of your values is 1 where your database doesn't support integers
hey @brazen raft
hmmm this is my db
yes look how you set it up
c.execute("""CREATE TABLE IF NOT EXISTS games (
member_id INTEGER UNIQUE,
character TEXT,
level INTEGER,
wins INTEGER,
money INTEGER,
attack_1 TEXT,
level_1 INTEGER,
attack_2 TEXT,
level_2 INTEGER,
attack_3 TEXT,
level_3 INTEGER,
attack_4 TEXT,
level_4 INTEGER,
miximax TEXT ,
eg TEXT,
tactic TEXT,
stadium TEXT
)""")```
okay and which column are you trying to input 1
first one is money
second one is miximax
money=int(50000)
miximax=str('Unlocked')
d.execute("""
UPDATE games
SET money = money - ?
WHERE member_id = ?
""", (money, member_id))
d.execute("""
UPDATE games
SET miximax = ?
WHERE member_id = ?
""",
(miximax, member_id))
conn.commit()```
well miximax is wrongly tabulated but in python is good
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
what to do ?
can u send code pls without that idk what to do xD
the argument ctx is used in the function
def your_function(ctx):
oh yeah u forgot ctx ig
shouldnt it be async def?

i have no idea if it's an asynchronous function or not
async def embed(self, ctx):
embed_message = discord.Embed(title="Title of embed", description="Description of embed", colour=discord.Colour.orange)
embed_message.set_author(name=f"Request by {ctx.author.mention}", icon_url=ctx.author.avatar)
embed_message.set_thumbnail(ul=ctx.guild.icon)
embed_message.set_image(url=ctx.guild.icon)
embed_message.add_field(name="Field name", value="Feild value", inline=False)
embed_message.set_footer(text="This is the footer", icon_url=ctx.author.avatar)```
i did this
why ctx.author.mention
it is easier to do a interaction command and do an interaction.user imo
my bot is not showing correct guilds member pls tell me how to fix this
memberCount = len(set(bot.get_all_members()))
await ctx.send(f"So im in {serverCount} guilds with a total of {memberCount} members. :smiley:\nIm running python {pythonVersion} and discord.py {dpyVersion}")
```
do u mind me changing your code?
no
Fix what
bot is not showing correct stats
ok go dm
try py len(bot.guilds)
oh you're trying to get the total members
bot.get_all_members() is a generator
do you have permissions for that
yea
i am bot owner
hm so what i should do to get the total members
total_members = 0
for guild in bot.guilds:
total_members += guild.member_count```
try that
or py total_members = sum(guild.member_count for guild in bot.guilds)
len([m for m in bot.get_all_members()])
!d discord.Client.get_all_members
for ... in get_all_members()```
Returns a generator with every [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") the client can see.
This is equivalent to:
```py
for guild in client.guilds:
for member in guild.members:
yield member
@dull terrace u dont see the problem ig right^^'
cause i cant find it either:""""")
i don't have enough information. you need to print stuff out and see what the issue is.
how should i do that?
self is necessary in async def (self, ctx)?
I donβt think so
embed.set_thumbnail(url=β. . .β)
You forgot the r ryuko
make a group Iβll try to help
ok
The function expects two arguments self and ctx but it should expect only one (it should expect only ctx). The tutorial you are following is terrible if you are using bot.command with self. self is a parameter of methods which are functions inside classes, and you didn't override the bot class and used commands.command instead of bot.command
**it is again showing this **So im in 15 guilds with a total of 15 members.
you dont have member intents
!d discord.Intents.members
Whether guild member related events are enabled.
This corresponds to the following events...
the only members visible is the bot's member itself
so how to get member intents
@slate swan
enable from dev portal and enable in your code using your discord.Intents instance
!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.
this is enabled ok let me check in dev portal
bro in dev portal my bot's intents are enabled and i also enabled intents in code still not fixed
ok show you intents code then
okay i am sending whole code of bot just wait
The constructor suffices
