#discord-bots
1 messages · Page 151 of 1
!d discord.ext.commands.Context.guild this returns the guild in which the command was executed
Returns the guild associated with this context’s command. None if not available.
Explanation 
What is the difference between instance and class?
Sorry, I am learning and coding together
The class is the "template" for an instance
An instance is when a class is called and then an instance of the class is created
Typically it has an init method which runs when an instance is created but it doesn't necessarily need one
class Foo:
...
bar = Foo()
Foo is a class, bar stores an instance of the class Foo
for name in lista:
instance = Guild.create_role(name=name)
await instance```
I changed to this
Still getting the same error
^
A class is similar to a cookie recipe
An instance is similar to the actual dish you can eat
Doing discord.Guild.create role is similar to adding salt to the paper containing the recipe
ctx is an instance of commands.Context, therefore it has an attribute called guild (as shown in the docs) which returns what you need
You want an actual instance to perform actions on
Analogous to using a recipe to actually make an edible dish, then adding salt to that
it is still confusing
you could read https://realpython.com/python3-object-oriented-programming/
I guess it's no use to try to code a bot right now...
Maybe I should exercice some OOP
discord bots aren't the most beginner friendly projects to work on 🤷
I tried to advence before
Brush up on some of the core principals of OOP and classes etc, then come back and see how you feel
Projects that challenge your existing knowledge are pretty good as long as you have that knowledge to an extent
That's what I need
Then OOP is a great start
hello, ive been cleared by the mods to request and receive help in making my recording bot, ive made a bit of progress but im stuck on some stuff.
this once_done line is a bit confusing i would appreciate help understanding it
vc.start_recording(
discord.sinks.WaveSink(), # the sink type to use
once_done, #what to do when done
ctx.channel #the channel to disconnect from
)```
What library are you using?
pycord
I know this isn't python, but does anyone know if D++ is a good C++ wrapper?
ive never attempted a project like this so im a bit/ extremely green about understanding whats goin on
Ah, sorry. Don't have any experience with that :P
Just for the record, we did clear them 👍
yeah to be extra transparent im building a tool to record podcasts in VC and im aiming for multi speaker recordings, ive seen my boss do this in pycord but im supposed to find out without asking him so im trying to get some help on it. the bot has extremely clear alerts that it is recording, and i will be adding in a ping to users in the VC to make them EXTRA aware. there are 0 ethical concerns and in the future id like to be able to create a speaker role so only those with the role can be recorded in general to allow the rest of the users to speak freely during recordings
i want it to be able to hop into a VC with like 4 ppl and record 4 sets of audio so that the user can receive the audio and master it on their own.
i want to add my SelectOptions in an __init__ function while sub classing discord.ui.select using discord.py
but i have used select.append_option to add options
how can i add them in __init__ funtion?
Unfortunately... discord voice recording documentation is... subpar, practically nonexistent :/
Maybe some libraries have it documented. Like in Java cord or whatever it was
I know d++ also has it iirc?
anyone?
@commands.slash_command(name = 'say', description="Сказать от имени бота. \n Пример: /say сообщение")
@commands.has_permissions(administrator = True)
async def ___say__(self, interaction: discord.Interaction, *, message):
if commands.MissingPermissions():
embed = discord.Embed(description = 'ERROR', colour=0x2F3136)
await interaction.response.send_message(embed=embed)
return
embed = discord.Embed(colour=0x87CEEB)
embed.add_field(name='**Объявление**', value= message, inline=False)
await interaction.response.send_message(embed=embed)```
how can I make it so that if a participant does not have administrator rights , an error is given to him when writing a message ??
all logical more logical ways don't work. although what is the logic in Python. He's worse than a girl who has her period...
make another class
@slash_command.error
its discord.py right?
thanks. I realized that this is a useless function
nice
yes
do you need a new class for each new team , or is it possible to do everything in one ?
async def <name>(ctx, error):
if isinstance(error, <Error_type>):
await interaction.response.send_message("<message you want to send>")
for example
async def purge_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You cant do that!")```
Yeah it's really hard. The person I've seen do it is really smart and did it alone in like 10 mins but I'm stuck looking
I think you have to make different classes for different errors
but there are other methods too
I know how to create an event error handler. I wanted to make such a handler purely for one command
replace the function name with the command name and it will work for that command only
@commands.slash_command(name = 'say', description="Сказать от имени бота. \n Пример: /say сообщение")
@commands.has_permissions(administrator = True)
async def say(self, interaction: discord.Interaction, *, message):
embed = discord.Embed(colour=0x87CEEB)
embed.add_field(name='**Объявление**', value= message, inline=False)
await interaction.response.send_message(embed=embed)
@say.error
async def on_say_error(self, error, interaction: discord.Interaction):
if isinstance(error, discord.ext.commands.errors.MissingPermissions):
await interaction.response.send_message("<message you want to send>")```
it didn't work. And there is no error in the console either
@timid spade
@bot.command()
async def partner(ctx, guild):
if ctx.author.guild_permissions.manage_messages:
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute("SELECT ad, adchannel FROM users WHERE guild = ?", (ctx.guild.id,))
guild1 = await cursor.fetchone()
await cursor.execute("SELECT ad, adchannel FROM users WHERE guild = ?", (guild,))
guild2 = await cursor.fetchone()
if guild is None:
await ctx.send("You dont have an ad/adchannel setup.")
else:
if guild2 is None:
await ctx.send("The guild your trying to partner with doesnt have an ad/adchannel setup.")
else:
channel = guild1[1]
ad = guild1[0]
channel2 = guild2[1]
ad2 = guild2[0]
await channel.send(ad2)
await channel2.send(ad)
why does this send no message/
i think the sytax is different for slash commands
did you try using if statements
.
Discord bots can use animated emojis no matter what right?
As long as its an emoji from the server
use from any server
await cursor.execute('UPDATE users SET id = ? WHERE ad = ? AND guild = ?, AND welcomechannel = ?, AND announcechannel = ?, AND welcomemessage = ?, AND leavemessage = ?, AND adchannel = ?', (member.id, '', ctx.guild.id, 0, 0, '', '', 0,))
Traceback (most recent call last):
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 140, in setup
await cursor.execute('UPDATE users SET id = ? WHERE ad = ? AND guild = ?, AND welcomechannel = ?, AND announcechannel = ?, AND welcomemessage = ?, AND leavemessage = ?, AND adchannel = ?', (member.id, '', ctx.guild.id, 0, 0, '', '', 0,))
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 129, in _execute
return await future
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 102, in run
result = function()
sqlite3.OperationalError: near ",": syntax error
The above exception was the direct cause of the following exception:
File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/cross-ad-bot/venv/lib/python3.8/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: OperationalError: near ",": syntax error
its working for me
What library is this-
that and if im not mistaking there aren't any up-to-date py libs that actively use voice recording. I've only known of js ones.
pycord and nextcord are uptodate and supports voice recieve
await msg.edit(embed=bans_kicks_msg[0].set_field_at(index=0,name="Test",value="0"))
TypeError: 'Message' object is not subscriptable
Got a working POC 🥶 hella type errors because Event[...]
bans_kicks_msg.embeds[0]
miss that, thank you
disable pyright on strict and watch your problems go away
Probably
It's only screaming because it's Unknown since no types have been passed
Lovely
how does POC look so far
POC?
proof-of-concept
I need to add gateway polling, rest and ratelimits then it should be off to models
Maybe rin is possible in 2022 after all
but shouldn't it automatically decide the type when you're initialising the Event class there itself
It's unknown
Then you abandon it after 3 days
ohh makes sense
Not bad, pretty nice implementation
It exists because callback signature (str) -> Coroutine[Any, Any, Any]
So if it is instead (int) -> ... it'll type error
how do i
make a bot that that gets information on a roblox playert
import discord
from discord.ext import commands
from discord import app_commands
import requests
response = requests.get("https://api.roblox.com/users/905112394")
client = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@client.command()
async def info(ctx, response):
await ctx.send(response.text)
client.run(no)
heres my code
Fortnite?
Also Yabai WM & Neovim
My terminal has transparency so that's just my wallpaper not a theme specific bg on neovim
I want to redo it since my file tree config sucks ass
I wanna switch over to flat colours and what not
I need help with my code
role = discord.utils.find(lambda r: r.name == 'Member', ctx.message.guild.roles)
username = client.get_user(user_id)
user = discord. utils. get(ctx.guild.members, )
if role in username.roles:
print("Role detected")
else:
print("No Role Found")```
Im trying to make it detect if they have the Member role but I get this error:
`NameError: name 'client' is not defined`
Can anyone help?
if guild2 is None:
await ctx.send("The guild your trying to partner with doesnt have an ad/adchannel setup.")
if guild1 and guild2 is not None:
ad, channel = guild1
ad2, channel2 = guild2
emb = discord.embed(title=f'Partnership From {guildid}', description=f'{ad2}')
em = discord.embed(title=f'Partnership From {ctx.guild.id}', description=f'{ad}')
channel = int(channel)
channel2 = int(channel2)
await channel.send(embed=emb)
await channel2.send(embed=em)
this isnt sending any messages, anyone help?
guildname = guild
guildname = bot.get_guild(guildname)
print("partner1")
ad, channel = guild1
ad2, channel2 = guild2
print("partner2")
emb = discord.Embed(title=f'Partnership From {guildname}', description=f'{ad2}')
print("partner3")
em = discord.Embed(title=f'Partnership From {ctx.guild}', description=f'{ad}')
print("partner4")
channel = bot.get_channel(channel)
channel2 = bot.get_channel(channel2)
await channel.send(embed=emb)
await channel2.send(embed=em)
print("partner5")
keeps saying None even tho im getting the guild
channel2=bot.get_channel(int(channel2)
The bot must be in that server to get the name and other information
it is
you made me realize I was calling a obj not a int
Yep
guild=bot.get_guild()
For guild information
ik
Nice
but guild was already got
so guild8 = guild
guild = bot.get_guild(guild)
guildid = guild8
guildname = guild8
guildname = bot.get_guild(int(guildname))
🤷
Guild name?
I was trying to get guild on the bottom part
It should guildid tho
guildname = guild8
which is a id'
Can u show the full code?
y
it's kinda hard to understand 🌚
Like what is the var guild
async def partner(ctx, guild):
ctx, guild: int):
guildname=bot.get_guild(guild)
guildname.name
guildname.id
guildname.owner_id
like dat
for paginator how can i append pages in a loop to where its a separate page for each entry? or simply implement a counter per page?
because right now im getting a very long paginator embed but instead i want each entry on its own page
Counter not always better as because it will always goes up while others are clicking too 🤷
But u can use counter too tho
its one person cmd with ephemeral send
but my problem is i cant just simply embed[i] and use i as counter yk
Then use counter, recommended
i=[]
Nvm xd
i=0 *
yeah but how do i differentiate the embed?
embed=[embed1,embed2,embed3]
then if user clicks a button i should be 0 tho
yeah i got everything else in the noggin
i just need to figure out how to separate these embeds
If i is 0 then it will send the first embed means embed 1
then second click
i will be 1
then
embed[i] will send 2nd embed means embed 2 from the list
In coding language counter starts from 0
for x in y:
Page(
embeds=[embed.add_field(name='name', value=info)],
)
result.append(embed)```
But from ourselves is 1
embeds*
its because im adding fields to embeds not making them
Xd
U have to make separate embeds xd
yes ty lmao
Ye xd
When I use Bot.unload_extension , does it automatically remove all commands added in the setup function for Bot.load_extension?
Yes
anything related to the module actually
https://github.com/Rapptz/discord.py/blob/799e3c5bf09cedcd9b7e2b83df733910fa11532a/discord/ext/commands/bot.py#L885
discord/ext/commands/bot.py line 885
async def _remove_module_references(self, name: str) -> None:```
also do slash command default perms work on subcommands?
Yes, the subcommand's default permissions are set to whatever the parent's default permission is. You can't have a single subcommand with a different permission though iirc
oh
subcommands are just command options in the shadows lol
I use for spaces in slash command 
How can I put the .append options in discord.ui.select()?
I used loops to append options in selection menu now I have to put them in discord.ui.select()
there's an options kwarg in the decorator, use it?
How can i get the list of people who can send messages in a channel?
You can iterate over channel.members and use if channel.permissions_for(<member>).send_messages
Got it, Thanks.
await user.edit(nick=new_nick)
It edits the user's nickname but after that it just gives an error in the console
User object don't have edit method 🤷
!d discord.Member.edit
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below...
/root/.pm2/logs/bot-error.log last 15 lines:
0|bot | Ignoring exception in on_ready
0|bot | Traceback (most recent call last):
0|bot | File "/usr/local/lib/python3.8/dist-packages/nextcord/client.py", line 502, in _run_event
0|bot | await coro(*args, **kwargs)
0|bot | File "/home/Runa/bot/main.py", line 22, in on_ready
0|bot | bot.db=await aiosqlite.connect('../db/level.db')
0|bot | File "/usr/local/lib/python3.8/dist-packages/aiosqlite/core.py", line 137, in _connect
0|bot | self._connection = await future
0|bot | File "/usr/local/lib/python3.8/dist-packages/aiosqlite/core.py", line 102, in run
0|bot | result = function()
0|bot | File "/usr/local/lib/python3.8/dist-packages/aiosqlite/core.py", line 397, in connector
0|bot | return sqlite3.connect(loc, **kwargs)
0|bot | sqlite3.OperationalError: unable to open database file
can someone help me with my error please?
@bot.event
async def on_ready():
bot.db=await aiosqlite.connect('../db/level.db')
bot.db=await aiosqlite.connect('../db/bank.db')
bot.db=await aiosqlite.connect('../db/blocked.db')
db=sqlite3.connect('../db/main.sqlite')
wut da hek
Why are you making multiple database files instead of just multiple tables?
And why use sqlite3 and aiosqlite togethe
its my first time making a bot. could that be whats causing the error? it was working before
what are the db’s storing? could probably all be applied and stored in one db under a user id
bank db is economy, so storing peoples wallet and bank
blocked is just a list of user ids
giveaway actually has nothing in it, i should prob delete it
level is a leveling database, so ppls level and exp
and main sqlite is for loading all my cogs
just think about what can be combined
ah okay
@client.tree.command(name='clear', description='deleteing messages')
async def purge(interaction: discord.Interaction, amount=int):
if (not interaction.user.guild_permissions.manage_messages):
embed=discord.Embed(title='Error :x: ', description=f'You don\'t have the permissions to run this command', color=0xe20909, timestamp = datetime.utcnow())
embed.set_footer(text='Created by UniqueDolphin#8001')
await interaction.response.send_message(embed=embed)
return
amount1 = amount+1
if amount1 > 201:
embed=discord.Embed(title='Error :x: ', description=f'I can\'t delete more than 200 messages at one time!', color=0xe20909, timestamp = datetime.utcnow())
embed.set_footer(text='Created by UniqueDolphin#8001')
await interaction.response.send_message(embed=embed)
else:
await interaction.channel.purge(limit=amount1)
embed=discord.Embed(title='Succeeded :white_check_mark: ', description=f'i have deleted `{amount}` messages!', color=discord.Color.green(), timestamp = datetime.utcnow())
embed.set_footer(text='Created by UniqueDolphin#8001')
await interaction.response.send_message(embed=embed)
This is the error
amount=int is not valid, you're saying this equals a type, rather then annotating it
so how do i fix this?
you would annotate it the same way you did with interaction: discord.Interaction, replace the equal sign with a colon
please help me fix my error @slate swan
whats your error?
the file is probably open somewhere else
or it doesnt have permissions to access the file
maybe something opened it to modify and didnt close
¯_(ツ)_/¯
whats this my code is for a mass dm bot i runned and that error occured
may want to read !rules
now giving me this
interaction.guild is None, this command was likely sent in DMs if the interaction does not have a guild attribute
yeah
wdym permissions?
then how can i do that?
how to fix it
this is how i do this
you need to defer first, the interaction is taking more than 3 seconds to respond
thats the error, defer it or check
@flat pier its saying error here anywhere?
rip gl with that
gl?
#rules 5 what you're making breaks ToS and abuses the API
I dont understand?

aah aah
its taking too long so you need to defer it so it doesnt die while loading basically
come dm once
ohhhhh ok
if the interaction takes more than 3 seconds to respond you need to "defer" the interaction, later you'll edit the original response (the defer response) with your message
you are basically saying, yes im doing something its just taking a second
so i just add to the command
await defer(....)
?
You respond to the interaction with defer then you can followup later and send whatever message you need to send
idk what library you're using
I just assume everyone is using dpy until they say they aren't
await inter.response.defer(...)
# some code here
await inter.edit_original_response(...)
anyone know if theres something specific I need to have "supports commands" on my bot? I use to have it on another one and its not showing up on my new one. My slash commands are registered and I have tried to make the bot public etc.
maybe you're slash commands aren't globally registered
You just have to have global slash commands as far as i know
thank you
Guys, how long can I edit a message for before it doesnt work? Im editing a message once every 5 seconds but after 15 or so minutes it stops working
Is there a way to avoid this>
is the message a response of an interaction?
it's a slash command so not sure
just a slash command that get's edited every 5 seconds
slash command that creates an embed
then I use await inter.edit_original_message(embed=embed)
you can't edit slash command responses after 15 minutes ( the interaction token expires)
just send a normal message instead
class select_channels(nextcord.ui.View):
def __init__(self, ctx_or_interaction, *, timeout=20):
super().__init__(timeout=timeout)
self.ctx_or_interaction = ctx_or_interaction
if isinstance(ctx_or_interaction, Context):
self.user = ctx_or_interaction.author
if isinstance(ctx_or_interaction, Interaction):
self.user = ctx_or_interaction.user
async def interaction_check(self, interaction):
if self.user == interaction.user:
return True
else:
await interaction.response.send_message(content="You are not allow to select the channel!")
@nextcord.ui.channel_select(channel_types=[nextcord.ChannelType.text], max_values=1, placeholder="Please choose one channel")
async def on_select(self, select: nextcord.ui.ChannelSelect, interaction: nextcord.Interaction):
channels = select.values.channels
for channel in channels:
print(channel.id)
data_default = {"_id": interaction.guild.id}
data = {"_id": interaction.guild.id, "global_id": channel.id}
await interaction.client.settings.upsert(data_default, data)
eb = self.children[0]
eb.disabled = True
eb.placeholder = f"You selected #{channel.name}"
reply = nextcord.Embed(description=f"{config.DiscordTic} Thanks! You have activated your global chat. --> <#{channel.id}>", colour=config.green)
await interaction.response.edit_message(embed=reply, view=self)
async def on_timeout(self):
eb = self.children[0]
eb.disabled = True
await self.message.edit(view=self)```
future: <Task finished name='discord-ui-view-timeout-e16c45d06ac9e9f60e732158c508ea01' coro=<select_channels.on_timeout() done, defined at c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup\views.py:195> exception=AttributeError("'select_channels' object has no attribute 'message'")>
Traceback (most recent call last):
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup\views.py", line 198, in on_timeout
await self.message.edit(view=self)
AttributeError: 'select_channels' object has no attribute 'message'```
Where is message attribute defined?
Are you using slash command or prefix command
slash
Since the send_message don't return anything, you have to set the message attribute for the view somehow, like with original_response, then edit it later.
view = ...
await interaction.response.send_message(...)
view.message = await interaction.original_response()
Or store the interaction that triggers the slash command and use edit_original_response.
view = ...
view.slash_interaction = interaction
await interaction.respose.send_message(...)
Thank you @naive briar
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 512, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 191, in on_application_command_error
raise error
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 910, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup\cog.py", line 549, in global_chat
await inter.client.settings.unset(unset_date, unset_field)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\alaric\document.py", line 377, in unset
await self._document.update_one(filter_dict, {"$unset": {field: True}})
TypeError: unhashable type: 'dict'```
case "delete":
dict_one = {"_id": inter.guild.id}
exists_check = await inter.client.settings.find(dict_one)
if exists_check is not None:
if "global_id" in exists_check:
c = inter.client.get_channel(int(exists_check["global_id"]))
if c:
question = nextcord.Embed(description=f"{config.DiscordSupport} Are you sure to deactivate the global Chat ({c.mention})?")
view = Yes_OR_No()
await inter.response.send_message(embed=question, ephemeral=True, view=view)
view.message = await inter.original_message()
await view.wait()
if view.value is None:
return
elif view.value:
unset_field = {"_id": inter.guild.id, "global_id": c.id}
unset_date = {"_id": inter.guild.id}
await inter.client.settings.unset(unset_date, unset_field)```
I use alaric
What is client.settings
A document
No a db document
Seems like #databases issue, provide traceback and last 3 lines of your code cause they are ones that cause the error, I'm not familiar with mongo so can't help by myself unfortunately
is there any way to delete buttons from a message in discord.py?
await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
i want to make a command to dm server owners to inform them about new features added to my bot. theres probably not a good way to do that is there?
by 'good way' i mean without negatively affecting my bot in discord for sending too many dms
did you mean
using the basic dm command
yea but i dont want discord to do anything dumb for sending too many dms to new users
mh
@bot.command(name = "mp", aliases = ["dm","MP","DM"])
async def Mp(ctx, user: nextcord.Member = None,* , msg):
if user == None:
user = ctx.author
if ctx.message.author.guild_permissions.administrator or ctx.author.id == 915096932005863464:
await ctx.message.delete()
try:
await user.send(msg)
except:
try:
await ctx.author.send(f"Le membre a fermé ses DMs")
except:
return
else:
await ctx.reply("Tu n'as pas la permission `Administrateur`.")
@mighty pilot do you want me to translate it?
bc its french
no need. i know how to make the command
my question was about how to avoid negative effects from sending too many dms to new users at once
because im sure discord watches that
great idea
since you got a report from a random yea
ill prob push update notifications another way
gl
make a mail command and keep sending messages in the mail store in db
You gotta face consequences sometime
If you don't want to, then don't do it
yea i think im just gonna push it to the associated servers botspam channel if they have it set for my bot. if not then they wont get an update
make a feature where server admins can set a designated updates channel?
i might do that
for now im going to send it to the bots channel but i may add a designated updates channel if its a requested feature
are you asking how to print hi in python?
oh you are trying to eval with a discord bot?
No no
Just want to get the String
the fact that its python 2 print code lol
in terms of a discord bot? or just in python in general?
print('Hi')
Umm just in Python i guess
Do I need regex or something?

i mean you said just in python and its right here
but you are giving me a weirdly minimal amount of info
/(hi)
can someone explain this error - discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range
!e
ls = [0,1,2]
print(ls[2])
print(ls[3])
thanks bro
hey, can anyone help me with setting discord bot? tag me in here and I will dm u
this is really important for me
learn to do it urself then
@shrewd apex :x: Your 3.10 eval job has completed with return code 1.
001 | 2
002 | Traceback (most recent call last):
003 | File "<string>", line 3, in <module>
004 | IndexError: list index out of range
who do you guys use for your discord bot hosting?
no free hosts if that's what u wanna know for paid or needs cc use aws or oracle vultr whichever one u want
Intel Pentium D 945, 3 GB DDR3 RAM, 250 GB slow HDD and drip 2000s case
Hi guys, I have my bot working, but when a put it on a server it wont reply, just in private msg
It needs message_content intent to access content of messages from servers
def willing to pay
!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.
but i'm going to be launching many many bots
I run like 10 bots there
nice
having trouble with that?
What 🐈
was just curious if you were having trouble with the intents
'Intents' object has no attribute 'message_content'
Nah, even if I am, I can Google
now im getting this error
intents = discord.Intents.default()
intents.message_content = True
Which library are you using and what is its version
from discord import Intents
from discord.ext import commands
from datetime import date
import calendar
That doesn't answer the question
I did smth but I have an error
That still doesn't
What library is in the toml file
[tool.poetry]
name = "repl_python3_Bot"
version = "0.1.0"
description = ""
authors = ["Your Name you@example.com"]
[tool.poetry.dependencies]
python = "^3.8"
discord = "^1.7.3"
[tool.poetry.dev-dependencies]
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
Bruh
u talking to me?
I see no problems
the thing is bot should answer smth by using events, but it doesn't
What events?
can we talk abt it in dms?
bro call i can someone to share my creen?
I don't talk about anything in my DMs 
lol
ah I guess I didn't put client event next to on_message function
ok guys I fixed it
!d discord.ext.commands.Context.author
Union[User, Member]: Returns the author associated with this context’s command. Shorthand for Message.author
The guild specific nickname of the user.
@nime.error
async def nime_error(self, ctx: commands.Context, error):
id = await self.db.fetchval("SELECT user_id FROM users WHERE user_id = $1", ctx.author.id)
if id is None:
raise id("error")
i want to make my own exception if, when entering a command, the user id is not in the database?
Just reply to the message?
!documentation
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
That check kwarg
Subclass CommandError so you can handle it in global handlers
class IDNotFound(commands.CommandError):
def __init__(self):
super().__init__("ID is not present in database")
# then to raise it
raise IDNotFound()```
!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.
Yeah but I'm unsure if name kwarg does automatic str cast
So to be safe cast it to str
Also for this case I recommend using @tasks.loop instead of event, as there might be suddenly many guilds adding the bot which will cause issues with channel renaming
You want user to reply to bot's message or smth
It does.
Still explicit is better than implicit 🤗
If there are already useless checks for it might as well use it and save some lines.
can i make a slash command only visible to a specific server?
i dont want to save the .txt in the folder just to sendpy ticket = f"ticket.txt" with open(ticket, "w") as file: async for msg in ctx.channel.history(limit=None, oldest_first=True): file.write(f"{msg.author.display_name}: {msg.clean_content}") file = discord.File(ticket) await send(file=file)
discord.File's first argument accepts a path to a file or a file-like object, like io.BytesIO
!d io.BytesIO
class io.BytesIO(initial_bytes=b'')```
A binary stream using an in-memory bytes buffer. It inherits [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase"). The buffer is discarded when the [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close "io.IOBase.close") method is called.
The optional argument *initial\_bytes* is a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) that contains initial data.
[`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO "io.BytesIO") provides or overrides these methods in addition to those from [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase") and [`IOBase`](https://docs.python.org/3/library/io.html#io.IOBase "io.IOBase"):
ah ok but how do i not save the file i just want to send it
Just pass the object in it, you can write it like a normal file
how should i do that should i remove (with open)
Demo:
with io.BytesIO() as fp:
...
fp.write(msg.clean_content.encode())
file = discord.File(fp, filename="meow.txt")
Since the io.BytesIO.write only accept a bytes object you need to encode your string
with io.BytesIO(ticket, "w") as fp:
async for msg in ctx.channel.history(limit=None, oldest_first=True):
fp.write(f"{msg.author.display_name}: {msg.clean_content}")
file = discord.File(fp, filename="data.txt")
await send(file=file)```
?
Did you see what I sent
yes
Your discord.File have to be in the with block
And fp isn't defined
And you don't need to set a mode for the bytes io
just
with (ticket, "w") as fp:
async for msg in ctx.channel.history(limit=None, oldest_first=True):
fp.write(f"{msg.author.display_name}: {msg.clean_content}")
file = discord.File(fp, filename="data.txt")
await send(file=file)```
with io.BytesIO() as fp:
async for msg in ctx.channel.history(limit=None, oldest_first=True):
fp.write(f"{msg.author.display_name}: {msg.clean_content}")
file = discord.File(fp, filename="data.txt")
await send(file=file)```
name 'io' is not defined
Then import it 
its too long
TypeError: a bytes-like object is required, not 'str'
Not trying to be rude but I'm not talking to you
I just explained
fp.write(msg.clean_content.encode(f"{msg.author.display_name}: {msg.clean_content}")
I
now ?
Okay
see what happens
dont work
!d str.encode
str.encode(encoding='utf-8', errors='strict')```
Return an encoded version of the string as a bytes object. Default encoding is `'utf-8'`. *errors* may be given to set a different error handling scheme. The default for *errors* is `'strict'`, meaning that encoding errors raise a [`UnicodeError`](https://docs.python.org/3/library/exceptions.html#UnicodeError "UnicodeError"). Other possible values are `'ignore'`, `'replace'`, `'xmlcharrefreplace'`, `'backslashreplace'` and any other name registered via [`codecs.register_error()`](https://docs.python.org/3/library/codecs.html#codecs.register_error "codecs.register_error"), see section [Error Handlers](https://docs.python.org/3/library/codecs.html#error-handlers). For a list of possible encodings, see section [Standard Encodings](https://docs.python.org/3/library/codecs.html#standard-encodings).
By default, the *errors* argument is not checked for best performances, but only used at the first encoding error. Enable the [Python Development Mode](https://docs.python.org/3/library/devmode.html#devmode), or use a [debug build](https://docs.python.org/3/using/configure.html#debug-build) to check *errors*.
Changed in version 3.1: Support for keyword arguments added.
😅
fp.write(f"{msg.author.display_name}: {msg.clean_content}")
fp.write(msg.clean_content.encode(encoding='utf-8'))```
with io.BytesIO() as fp:
async for msg in interaction.channel.history(limit=None, oldest_first=True):
fp.write(f"{msg.author.display_name}: {msg.clean_content}".encode())
file = discord.File(fp, filename="ticket.txt")
await send(content="You Log", file=file)```
what i need to do ?
Just move it down?
what i need to move down ?
in this code
with io.BytesIO() as fp:
async for msg in interaction.channel.history(limit=None, oldest_first=True):
fp.write(f"{msg.author.display_name}: {msg.clean_content}".encode())
file = discord.File(fp, filename="ticket_data.txt")```
?
it does not work
What does not work
But what
he not send nothing
fp.write(f"{msg.author.display_name}: {msg.clean_content}".encode())
What does that mean
you need to seek the file pointer back to the start after you finish writing to it, otherwise dpy cant read the contents of your file
he send the .txt but with nothing inside
e.g. ```py
fp = io.BytesIO()
fp.write(b'...')
fp.seek(0)
file = discord.File(fp, ...)
upload attachment as normal```
it works thanks
What do you need with it?
How do i dockerize my discord bot?
can you put an f-string inside an f-string? having trouble with storing a message inside a database then recalling it in a way that i can mention a user. it just prints {user.mention} instead of performing the mention.
ive tried moving the {} about everywhere i can with no success. if i type the message out into the code it works flawlessly
use python eval
You have to use different quotation marks but it works
num=10
expr="(2+(3*2))/2 + num"
print(eval(expr))
ill see if i can get that to work
Do not
A simple .format will do
do you have a link on docs for .format? im not too familiar with it and id like to learn more
!e
my_str = "{hello} {world}"
print(my_str.format(hello="hello", world="world"))
@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.
hello world
so youd store a variable as {mention} made it to {level} then when you recall it you need to reassign it with .format(mention=user.mention, level=newlvl)? (newlvl is a previously assigned variable)
yup
thanks
works flawlessly. i love you.
no worries
You didnt say "i love you more" or "i love you too", talk about being rude
oh shut up
see, robin is the rudest person ever, ban him🔨
yo, so every time I want to make changes in a file that's not a cog, I have to restart the bot, correct?
I'm asking because I have a python file called "Class Library" which includes a bunch of classes I use throughout all of my cogs. Every time I make changes to them, I have to restart the bot for those changes to take effect. Should I just put the contents of that file in a cog so I can just reload it for the changes to go through? Should I put ALL python files (like a utils file) other than main.py in cogs so I can reload them?
you could use watchdog (to know what file changed and get and event when a file changed) and importlib.reload to reload the module
how do i host a bot 24/7
@bot.command("ban")
@commands.has_permissions(ban_members=True, administrator=True)
async def ban(ctx: commands.Context, member: discord.Member) -> None:
await member.ban()
await ctx.send(f"Banned **{member.name}**")```
`Traceback (most recent call last):
File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 18, in ban
await member.ban()
File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/member.py", line 722, in ban
await self.guild.ban(
File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/guild.py", line 3454, in ban
await self._state.http.ban(user.id, self.id, delete_message_seconds, reason=reason)
File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/http.py", line 738, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/Lost-Aura/venv/lib/python3.8/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: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions`
is it because i dont have missing permissions imported? or with discords.py 2.0 is it all under one import
help
huh
!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.
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
it gives me missing permissions and i dont even have missing permissions in any of my commands
what do you mean by reload the module?
how to check is_super_admin() or is_admin(), help me
importlib.reload allows you to reload a module at runtime, so the changes will be usable without restarting the Bot
iirc you need also to reload the cog that is using the reloaded module
oh! so I could reload the file and my script could continue to run? is that a popular practice?
or the extension
yeah, this is no issue. I'm already used to doing that
guys how to unban using discord id?
hello, u can help me?
not much, but a few months ago I had to do a project about it so I worked a bit with watchdog, usually these things are done by those who design libraries or advanced Bot projects
i see. do most people just restart the bot whenever they make changes outside of a cog then?
!d discord.Guild.unban
await unban(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to do this.
yea but instead of discord.Member i need it to unban and make the user ID as the identifier
how to check is_super_admin or is_admin in this code? plsss
check again syntax, tab or white space
no clue
u can show error?
@trim shadow
show line code that
u can not "if" in like 395
like:
if ...:
mine15 = ...
elif c = ...:
...
you write like that? right?
why not just use something like c in [...]?
When you have a bunch of if/elif it's a sign that you should re-write or rethink code structure
of course the actual issue lies with indentation
write follow your code
ok?
yes, that example
@client.tree.command(description="Delete a mass amount of messages")
@app_commands.rename(amount="amount")
@app_commands.describe(amount="Number of Messages")
@app_commands.checks.has_permissions(manage_messages=True)
async def purge(interaction: discord.Interaction, amount: int):
if amount == 0:
await interaction.message.response.send_message(
f"Amount must be more than 0",ephemeral=True)
return
await interaction.channel.purge(limit=amount)
if amount == 1:
await interaction.message.response.send_message(
f"{interaction.user} purged {amount} message")
return
else:
await interaction.message.response.send_message(
f"{interaction.user} purged {amount} messages")
return```
I need help
when I run the command I get this error:
```Traceback (most recent call last):
File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 263, in purge
await interaction.message.response.send_message(
AttributeError: 'NoneType' object has no attribute 'response'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: AttributeError: 'NoneType' object has no attribute 'response'
it should be interaction.response.send_message not interaction.message.response.send_message
thanks
It still doesn't work
Traceback (most recent call last):
File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
Looks like it might've taken too long for your application to respond to the interaction. It's usually good to defer the interaction as a first action, so that you can modify the response later without taking too long to respond
Idk what that means, I'm new to using interaction instead of ctx
Have you ever seen it where a bot will show "<bot name> is thinking..."?
no
oh
Well, that's what shows up when an interaction is defered
# defer at the beginning of your function
await interaction.response.defer()
... # do stuff
# send the response to replace the defered command's "thinking"
await interaction.followup.send("my response")
@client.tree.command(description="Delete a mass amount of messages")
@app_commands.rename(amount="amount")
@app_commands.describe(amount="Number of Messages")
@app_commands.checks.has_permissions(manage_messages=True)
async def purge(interaction: discord.Interaction, amount: int):
if amount == 0:
await interaction.response.defer()
await interaction.followup.send(
f"Amount must be more than 0",ephemeral=True)
return
await interaction.channel.purge(limit=amount)
if amount == 1:
await interaction.response.defer()
await interaction.followup.send(
f"{interaction.user} purged {amount} message")
return
else:
await interaction.response.defer()
await interaction.followup.send(
f"{interaction.user} purged {amount} messages")
return
I changed it and still get the same error
defer as the very first thing
once at the very top at the function
That purge process probably takes a few seconds, so right now you aren't defering until after that has ended, which defeats the purpose of defering
File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message
now I get this
I know why, I think... the command message is getting deleted?
Yea, that would make sense, since your purging it
I have the following code
import discord
from discord.ext import commands
import speech_recognition as sr
intents = discord.Intents.all()
# Create a new Discord bot
bot = commands.Bot(command_prefix='!', intents=intents)
# Define a command that allows the bot to join a voice channel and start listening for voice input
@bot.command()
async def listen(ctx):
# Check if the bot is already connected to a voice channel
if bot.voice_clients:
# If the bot is already connected to a voice channel, disconnect from it
await bot.voice_clients[0].disconnect()
# Join the voice channel the user is currently in
voice_channel = ctx.message.author.voice.channel
await voice_channel.connect()
# Start listening for voice input
r = sr.Recognizer()
while True:
try:
# Wait for the user to say something
with sr.Microphone() as source:
audio = r.listen(source)
# Convert the voice input to text
text = r.recognize_google(audio)
print(text)
except:
print("No speech was said during this time")
# Run the bot
bot.run('My_Token')```
Why does this cause a Discord heartbeat blocked error?
that speech recognizer and that while true loop don't look async, so they probably block the whole program and don't let it send a heartbeat ping
How would I fix this? It it easy...
how to fix error indent
Not sure, never really done much stuff with discord voice. discord.py doesn't support receiving audio iirc
dang, I responded to myself
Is it possible to detect if a user has recently had voice activity eg talking?
In discord.py, I don’t think so
@bot.command("unban")
@commands.has_any_role("Founder","Leader","Recruiter")
async def unban(ctx: commands.Context, member: discord.Member) -> None:
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split("#")
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name,member_discriminator):
await member.unban(user)```
Traceback (most recent call last): File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke await ctx.command.invoke(ctx) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1015, in invoke await self.prepare(ctx) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 932, in prepare await self._parse_arguments(ctx) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 839, in _parse_arguments transformed = await self.transform(ctx, param, attachments) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 709, in transform return await run_converters(ctx, converter, argument, param) # type: ignore File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/converter.py", line 1340, in run_converters return await _actual_conversion(ctx, converter, argument, param) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/converter.py", line 1222, in _actual_conversion return await converter().convert(ctx, argument) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/converter.py", line 262, in convert raise MemberNotFound(argument) discord.ext.commands.errors.MemberNotFound: Member "694038289849647155" not found.
can someone help pleaseee?
A Member is a User who is part of a guild
Those are just variable names
You should use UserConverter instead of MemberConverter
You can typehint the parameter to discord.User instead
@bot.command("unban")
@commands.has_any_role("Founder","Leader","Recruiter")
async def unban(ctx: commands.Context, member: discord.User) -> None:
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split("#")
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name,member_discriminator):
await member.unban(user)```
because that would change anything that is labeled member to discord.User right
To unban the user you just use ctx.guild.unban(member)
yes but i wanna unban using user id
hello, i need example hybird command, plsss
hybrid command example github discord.py search it on google, and click on first link of github
if "#" in member:
#then this is ur code
else:
member=bot.get_user(int(member))
#other codes
Kind of easy,
What we did here?
Well we are checking if # is in the member argument or not of there then it will ban according to the name if not there it will get the user with user id
Yes
okay
#other codes i mean u can directly now do
if (member.name, member.discriminator)==(user.name, user.discriminator):
@pallid mango u can do kind of like dat
No need of
member_name and member_discriminator while doing with id
Altho ur code is kind of old tho 🌚
U can use...
yea it is before discord.py 2.0
and now im like super confused i tried reading the docs but got overwhelmed
Xd
i would imagine all of my code is old
Ahh
I got rigged when they changed member.avatar_url to member.avatar 💀
I had to change the whole code
!d discord.Guild.unban
await unban(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to do this.
@pallid mango easiest way to do
user=bot.get_user(id)
await guild.unban(user=user, reason=None)
Typehinting with discord.User will work with ids
And it will work with user#1234
But u can't mention them altho it will return the member object kinda cul
!d discord.ext.commands.UserConverter
class discord.ext.commands.UserConverter(*args, **kwargs)```
Converts to a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
All lookups are via the global user cache.
The lookup strategy is as follows (in order)...
await ctx.guild
It will be ctx.guild since u using prefix
@bot.command("unban")
@commands.has_any_role("Founder","Leader","Recruiter")
async def unban(ctx: commands.Context, member: discord.User) -> None:
user=bot.get_user(id)
await ctx.guild(user=user, reason=None)```
Ye this should work
okay
You don’t need the get user stuff. Just do await ctx.guild.unban(member, reason=None)
Oh ye cuz it will automatically converted to discord Object i assume
Yep
Cul
@bot.command("unban")
@commands.has_any_role("Founder","Leader","Recruiter")
async def unban(ctx: commands.Context, member: discord.User) -> None:
await ctx.guild.unban(member, reason=None)
await ctx.send(f"Unbanned **{member.name}**!")```
okay now how do i delete message after a little bit of time
like 10 seconds or something ik its super simple before update but idk now
await ctx.send(...., delete_after=10)
okay
!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 "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
Ye
@bot.event
async def on_member_join(member):
if member.guild.id != 1050564778361364530: return
welcome = bot.get_channel(1050564779493826570)
await welcome.send(f"Hello, {member}, welcome to Ace Public.")
await member.add_roles("Fans")```
can i have this bot control two different welcome channels server to server
Database
because its in both of my servers and the two servers correlate with one another or do i need a whole new bot
nope not me, whole new bot 🙂
The guild that the member belongs to.
Oh cool
well i mean like on join just send a welcome message
If a common welcome message with the diff server name and diff member mention is possible
@bot.event
async def on_member_join(member):
if member.guild.id != 1050564778361364530: return
welcome = bot.get_channel(1050564779493826570)
welcome1 = bot.get_channel(1050570584817418380)
await welcome.send(f"Hello, {member}, welcome to Ace Public.")
await welcome1.send(f"Hello, {member}, welcome to Ace Private.")
await member.add_roles("Fans")
await member.add_roles("ACE")```
would need two different events right?
if member.guild.id == urguildid:
welcome=.....
await welcome.send()
elif member.guild.id == anotherguildid:
#other code
I prefer using database 💀
and then the add roles
Yes
Do welcome to {member.guild.name}
Kind of like that
To get the guild name
@bot.event
async def on_member_join(member):
if member.guild.id == 1050564778361364530: return
welcome = bot.get_channel(1050564779493826570)
welcome1 = bot.get_channel(1050570584817418380)
await welcome.send(f"Hello, {member}, welcome to Ace Public.")
await member.add_roles("Fans")
elif member.guild.id == 1050570584280531065:
await welcome1.send(f"Hello {member}, congratulations, welcome to Ace Clan!")
await member.add_roles("ACE")```
okay so i know the elif is wrong
Ur indention is wrong
yea id say so
@bot.event
async def on_member_join(member):
if member.guild.id == 1050564778361364530:
welcome = bot.get_channel(1050564779493826570)
await welcome.send(f"Hello, {member}, welcome to Ace Public.")
await member.add_roles("Fans")
elif member.guild.id == 1050570584280531065:
welcome1 = bot.get_channel(1050570584817418380)
await welcome1.send(f"Hello {member}, congratulations, welcome to Ace Clan!")
await member.add_roles("ACE")```
ohhh
i could barely even see the difference on my monitor
everything look good on that one?
do you know how to fix this keep_alive this for replit
I am on mobile so, it's possible to lil things go wrong
i dont know of a better alternative
its for webserver
To make bot 24/7
yea everytime i set it up it just says too many requests
🤷
oooh i wonder if i need to use keep_alive if i have replit+ where it gives an option to run 24/7
Nice 🙂
guys how long have you been learning python and started coding py bots
people here are anywhere from 1month to using tally marks to remember the years
Python almost 2 years. Discord bots 1.5 years
I Started discord bots way too early
bro that early
i am barely learning from 7 months and in 3-5 months will earn all advance python and start to learn about coding bots
and then i wanna learn Lua too.
btw i am still a school today 💀
lua is meh
all i can imagine doing with lua is roblox plugins rn
I didn't learn any python before coding bots
this guy summoned me
Yo ur pfp sus also the text sus too

this guy's sarth in disguise
lmao 😔```py
@self.listen()
async def on_message(msg):
if "meh" in msg.content:
self.take_me_to_pydis()
dewit
BREAKING DC TOS :ALERT:
xd
import discord
from discord.ext import commands
intents = discord.Intents.all()
intents.message_content = True
intents.members = True
bot = commands.Bot(intents = intents, command_prefix = "!")
@bot.event
async def on_ready():
print('Ready!')
@bot.command()
async def test(ctx, arg):
await ctx.send(arg)
bot.run(TOKEN)
can someone explain why this just does not work
when i type the command nothing happens
yea token is correct and how do i enable intents in portal?
!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.
Go to ur apps
is your token “ “?
no token is correct other other stuff is working in the code
import discord
from discord.ext import commands
intents = discord.Intents.all()
intents.message_content = True
intents.members = True
redx = 280351437203177483
small_pp = 768589770343317536
bot_test_id = 1046566076831514634
bot = commands.Bot(intents = intents, command_prefix = "!")
@bot.command()
async def test(ctx, arg):
await ctx.send(arg)
@bot.event
async def on_presence_update(before, after):
if before.guild.id == 768589770343317534:
print(after.name)
print(after.status, "\n")
if after.id == redx and before.status == discord.Status.offline and after.status == discord.Status.online:
print("Redx is Online")
await bot.get_channel(small_pp).send("https://tenor.com/view/online-isaiah-gif-22767935")
if after.id == redx and before.status == discord.Status.online and after.status == discord.Status.offline:
print("Redx is offline")
await bot.get_channel(small_pp).send("https://tenor.com/view/offline-isaiah-gif-22767927")
@bot.event
async def on_message(message):
print(message.author.name, message.content, message.channel.id, message.guild.name)
server = bot.get_guild(bot_test_id)
if message.content.lower() == "!owner":
owner = server.owner
await message.channel.send(f"The owner is {owner.mention}.")
if message.content.lower() == "!hello":
await message.channel.send(f"Hi {message.author.mention}!")
if message.content.lower() == "!":
print("hi")
@bot.event
async def on_ready():
print('Ready!')
bot.run(TOKEN)
i just had a stroke reading that
Yes u have this problem
@bot.event
async def on_message(message):
await bot.process_commands(message)
Do it @shy kelp
It will process the message evnt
And let the prefix commands work too
If u don't process it, prefix commamds won't work

change .event on on_message to .listen()
async def on_message(message):
await bot.process_commands(message)
if before.guild.id.....
#start from here
He doesn't have another on_message evnt tho
i do
ill add ur thing to mine
I thought listen only works when u have 2 events 💀
@slate swan thanks xd
Still ur pfp 
its working now that i added it the the other on_message but whats .listen() ?
is it just a substitute for .event ?
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").
Example...
It doesnt override the internal event but it still listens for the event
U can't have 2
on_message main event so only the last on_message event wilk be called
If u use @bot.listen()
Then it will still listen on both of on_message evnt
nope you can use it whenever you want to
what about that lol
Yes
Ye i didn't know that 💀
Dm C....#.... For ;-;
\🍑
😂
sus
thats a joke, dare
Ik 💀
Can I use website hosting service to host my discord bot?
thats quite an interesting question, why would you?
Economic issues
i mean if you dont need a console and just STDOUT you can use smth like pebble for like $2
or an old laptop, raspberri pi for one time purchase host
STDOUT?
just use oracle, its free forever
need a credit card or debit card for verification tho
no console input but you can see outputs
Hmmm alright
https://paste.pythondiscord.com/cehecifohe
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 658, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1382, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 1524, in invoke
await ctx.invoked_subcommand.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 940, in invoke
await self.prepare(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 874, in prepare
await self._parse_arguments(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 780, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 624, in transform
return await run_converters(ctx, converter, argument, param)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\converter.py", line 1268, in run_converters
return await _actual_conversion(ctx, converter, argument, param)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\converter.py", line 1180, in _actual_conversion
raise BadArgument(f'Converting to "{name}" failed for parameter "{param.name}".') from exc
nextcord.ext.commands.errors.BadArgument: Converting to "int" failed for parameter "level".```
The library cannot convert the first argument you gave it to int
How did you invoked the command
wdym invoked
Call
like from a group
what did you type on discord to run that command
i dont rrlly understand the question
async def poll(message, x, y):
embed = discord.Embed(title="Poll", description=f"React with 1 for {x} or react with 2 for {y}", color=0xFF0000)
msg = await message.channel.send(embed=embed).add_reaction(1050671368968081459)```
The number in the add_reaction bracket is the id for the 1️⃣ emoji
i get this long error
just use .add_reaction(":one:")
You can't chain coroutines
await (await message.channel.send(...)).add_reaction(...)
Should work i think
It's worth pointing out the following issues with your code:
1: you should use .add_reaction() on the msg object.
2: it's also worth pointing out that the 1️⃣ emoji has no ID, you're probably pasting the ID of a message.
Tbf send returns a message object
But the second is accurate
well the issue with this approach is that you sacrifice readability
and you can't use the returned Message object again unless you also shove a walrus operator in there.
That's true
so how do i put 1️⃣ in there
is 1gb enough for a discord bot?
Depends?
What does it do, how many servers
currently 103 and increasing
and first question?
well it gives href links from websites using lxml as well as joins vc to play few sound effects stored in the bot files and search image provided from the user at a website using its api
prob around has 80-90 commands or less or more
hmm alright
usually yes, this approach is more for libraries or for specific extensions that aim to do something
maybe you could use this approach when you're in production, when you have a sharded bot and you don't want to wait hours to get the Bot back online on some servers (though idk if this would work)
depends on what kind of changes
usually you can use extensions
they are not meant to be used only with cogs
https://paste.pythondiscord.com/cehecifohe
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 658, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1382, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 1524, in invoke
await ctx.invoked_subcommand.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 940, in invoke
await self.prepare(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 874, in prepare
await self._parse_arguments(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 780, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 624, in transform
return await run_converters(ctx, converter, argument, param)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\converter.py", line 1268, in run_converters
return await _actual_conversion(ctx, converter, argument, param)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\converter.py", line 1180, in _actual_conversion
raise BadArgument(f'Converting to "{name}" failed for parameter "{param.name}".') from exc
nextcord.ext.commands.errors.BadArgument: Converting to "int" failed for parameter "level".```
@client.event
async def on_member_join():
await discord.Member.add_roles(discord.utils.get(discord.guild.roles, name = "member"))
This is not working
@glad cradle
on_member_join(member):
await member.add_roles(....)
i dont get it 🤡 .
How can I find out if a message was sent 30 minutes ago or not?
!d discord.ui.select
@discord.ui.select(*, cls=<class 'discord.ui.select.Select'>, options=..., channel_types=..., placeholder=None, custom_id=..., min_values=1, max_values=1, disabled=False, row=None)```
A decorator that attaches a select menu to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the chosen select class.
To obtain the selected values inside the callback, you can use the `values` attribute of the chosen class in the callback. The list of values will depend on the type of select menu used. View the table below for more information.
The options kwarg
i added options like this
!d discord.Message.created_at
property created_at```
The message’s creation time in UTC.
subtract it from current time to get a timedelta
use a Select subclass then, and add it to the view using View.add_item later
!d discord.ui.Select
class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu with a list of custom options. This is represented to the user as a dropdown menu.
New in version 2.0.
ok let me try
Like this?:
time = message.created_at
duration = time - currenttime(how to get this)
if duration > 30:
#...
I don't know how to work with timestamps
!d datetime
Source code: Lib/datetime.py
The datetime module supplies classes for manipulating dates and times.
While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.
!d discord.utils.utcnow
discord.utils.utcnow()```
A helper function to return an aware UTC datetime representing the current time.
This should be preferred to [`datetime.datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "(in Python v3.11)") since it is an aware datetime, compared to the naive datetime in the standard library.
New in version 2.0.
!d discord.utils.utcnow
Yo
discord.utils.make_a_bot() when
💀💀💀
Imagine if this would exist
for uptime? you can just store the datetime at which bot was launched
python -m discord newbot --prefix ? BotName does it but thats minimal
Traceback (most recent call last):
File "C:\Users\imac\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 169, in _loop
await self.coro(*args, **kwargs)
File "C:\Users\imac\IdeaProjects\Moamele\me\Moamele\net\main.py", line 637, in channelmanager
message = await channel.fetch_message(channel.last_message_id)
File "C:\Users\imac\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1686, in fetch_message
data = await self._state.http.get_message(channel.id, id)
File "C:\Users\imac\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 366, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In message_id: Value "None" is not snowflake.
import asyncio
from discord.utils import make_a_bot
async def main():
await make_a_bot(" free dollar generator no fbi".strip().title().beautify().fontify().vectorize())
asyncio.run(main())```
The future of IT
last_message_id is None
Read docs, it's optional
!d discord.TextChannel.last_message_id
The last message ID of the message sent to this channel. It may not point to an existing or valid message.
I printed the message, its not None
it even prints the time diff
msg_time = message.created_at
time = utcnow()
diff = time - msg_time
print(diff)
The way you phrased this implies that other languages/frameworks do have this capability, Is that true? If so, which language/framework is the best at present and how might I compare the quality of implementation in the various languages?
you could be interested on on_voice_state_update, this will allow you to detect when a member muted/umuted deafened/undeafened etc himself. Note that this doesn't make you exactly sure if the user is talking, to be sure if the user is talking you need to recive packets from the Voice client and perform some checks, currently Discord.Js and pycord (iirc) implements VoiceReceiver/s
!d disnake.on_voice_state_update
disnake.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://docs.disnake.dev/en/latest/api.html#disnake.Member "disnake.Member") changes their [`VoiceState`](https://docs.disnake.dev/en/latest/api.html#disnake.VoiceState "disnake.VoiceState").
The following, but not limited to, examples illustrate when this event is called...
With the new server subscription bs do you guys expect an update to discord.py and the forks to be coming?
if the api will support that for bots, each Library will implement it.
does anyone know which library to use to make telegram bots?
#python-discussion can provide faster answers
thank u
I think pycord has voice receiving
However voice receiving is an undocumented feature
Oop snipy already said that
async def coins(interaction: discord.Interaction, user: discord.Member = commands.Author):
is there any error ?
What does commands.Author even mean
if there is no argument given , the bot will chose the command's author as user
- this code was already given to me by someone in this server, and it was working
but with no slash commands
@naive briar any help ?
The annotation isnt correct
Your annotation is not correct?
why the string concatenation?
because its commented out?
i know
i commented it to try the other command
commands.Author doesn't work for slash commands
its a part of prefix command extension
interaction.user
yes^
!d discord.Interaction.user
The user or member that sent the interaction.
i can't , it's inside the parameters
you'll have to do it inside your command function
it's with the parameters , it will be definied with the interaction at the same time
just make the option Optional
if its None set the value to interaction.user
simple as that.
hmmm i'll try
U can use discord.Interaction.user too maybe
as this ?
File "C:\Users\user\Desktop\Other\Bots_For_Sell\GameOver bot\bot.py", line 31, in <module>
async def coins(interaction: discord.Interaction, user:None):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 889, in decorator
command = Command(
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 685, in __init__
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 393, in _extract_parameters_from_callback
param = annotation_to_parameter(resolved, parameter)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\transformers.py", line 832, in annotation_to_parameter
(inner, default, validate_default) = get_supported_annotation(annotation)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\transformers.py", line 791, in get_supported_annotation
raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'NoneType'>```
user=None 🙂
It will be that not with colon
that won't work
spooky smart
it will be definied as None always
user: discord.Member = None
....
it will work
everyone uses the same
thats how discord.py is designed
Altho without defining it if we just mention the member it should catch the object automatically isn't it?
I think so
as this ?
Yes
examples/app_commands/basic.py lines 69 to 76
# or you can mark it as Optional from the typing standard library. This example does both.
@client.tree.command()
@app_commands.describe(member='The member you want to get the joined date from; defaults to the user who uses the command')
async def joined(interaction: discord.Interaction, member: Optional[discord.Member] = None):
"""Says when a member joined."""
# If no member is explicitly provided then we use the command user here
member = member or interaction.user```
i still cant figure out that one problem
can you help? 🤡
yep
im sorry I don't remember what your original issue was , could you point it out again
i want to replace this
with this
U can lub him as a friend 💀
Can ya show whole code?
class Role_Select(Select):
def __init__(self) -> None:
super().__init__(max_values= max_val,min_values=min_val ,options=[discord.SelectOption(label='hm')])
async def callback(self, interaction):
user = interaction.user
await interaction.response.send_message(":arrows_clockwise: Thinking....", ephemeral = True)
await interaction.delete_original_response()
for item in roles:
role = get(ctx.guild.roles, name= item)
if item in self.values and role not in user.roles:
await user.add_roles(role)
elif role in user.roles and item not in self.values:
await user.remove_roles(role)
oh yeah wait i can show you an example how to make a select with a subclass
yes please
me and my crush in a nutshell
Why u adding select on init tho 🤷
🗿
@unkempt canyon yo ded guy
4k forks means ...
4k libraries??? xd
youtube guy did this
i tried hard to understand but he made it confusing
so i did what he did 🤡
💀💀
It's not good way to add select options xd
Ah cool
ok thanks
ik
I understood everything except this part so did what he did
i cant spot the error 🫠
does anyone know how to check my bot's permissions in my script?
i'm trying to check if I have manage_emojis permissions (which I should), but discord.Permissions.manage_emojis but it's just giving <flag_value flag=1073741824>
bot.Permissions doesn't seem to work - i think I'm misunderstanding the documentation



