#discord-bots
1 messages Β· Page 28 of 1
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
you got this?
@commands.command()
async def roles(self, ctx, member: discord.Member):
"""
don't mind this
"""
member = ctx.author or member
embed = discord.Embed(title=f"Roles {member} have: ", description=f"\n".join([role.name for role in member.roles]), color=discord.Colour.dark_theme())
await ctx.send(embed=embed)
``` no response π
do i actually need this because other commands work normally without this
you need this if you wanna work with members
ok
why is it ctx.author or member
you switched that
the message popped up but the role is not being added
member or ctx.author?
yeah
I really don't know why
π’
both codes seem good to me
@commands.command()
async def selfroles(self, ctx, member: discord.Member):
member = member or ctx.author
embed = discord.Embed(title=f"Roles {member} have: ", description=f"\n".join([role.name for role in member.roles]), color=discord.Colour.dark_theme())
await ctx.send(embed=embed)
``` sstill no response
Add role b4 the message and see if it sends the message
that's smart
Await ctx.send
do you have members intents?
Nvm
Can u send a ss, this is indented weird on the phone
I have intents.default in my code
And Iβve enabled all intents I can from dev portal
Set it to intents.all in ur code
Still the same
its not sending the message if i move role b4
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
Traceback (most recent call last):
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'text_channel_count'
help pls, Im not good with embeds
@bot.command(aliases=['Serverinfo', 'ServerInfo'])
async def serverinfo(ctx):
embed = discord.Embed(title = f"{ctx.guild.name} Info", color = discord.Colour.blue())
embed.add_field(name = ':2093wumpus: Server ID', value = f"{ctx.guild.id}", inline = True)
embed.add_field(name = ':5955squaredownloadupdate: Created On', value = ctx.guild.created_at.strftime("%b %d %Y"), inline = True)
embed.add_field(name = ':owner: Owner', value = f"{ctx.guild.owner}", inline = True)
embed.add_field(name = ':admin: Members', value = f'{ctx.guild.member_count} Members', inline = True)
embed.add_field(name = ':5505discordchannelsfromvega: Channels', value = f'{ctx.guild.text_channel_count} Text | {ctx.guild.voice_channel_count} Voice', inline = True)
embed.add_field(name = ':7080redearth: Region', value = f'{ctx.guild.region}', inline = True)
embed.set_thumbnail(url = ctx.guild.icon_url)
embed.set_footer(text = ":star: β’ Duo")
embed.set_author(name = f'{ctx.author.name}', icon_url = {ctx.message.author.avatar_url})
await ctx.send(embed=embed)
can i do it with discord.utils
Print out role
Keep it as it is and print it out
replace guild.text_channel_count with len(guild.text_channels)
and same with voice channels
k
you printed it after add_roles...
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'len'
not ctx.len()
Code?
should i delete ctx then?
This ^
ok
did you do
bot = commands.Bot(..., intents=discord.Intents.all())
Oh wait I did it somewhere else
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.author.icon_url: Scheme "{<asset url='/avatars/898629552702644317/21e8c0bc6288730afd9fc82f8b5aba7d.webp?size=1024'>}" is not supported. Scheme must be one of ('http', 'https').
after fixing that i get this
what should i do?
Still no response
remove the {} from icon_url = {...}
let it just be icon_url = ...
k
k
thank you its finally working!
π
@bot.command()
async def redeem(ctx, code):
if code == "deptrainhatsv":
role = ctx.guild.get_role(1006198515438981170)
print(role)
await ctx.send("key successfully redeemed")
else:
await ctx.send("key not found")
i dont have add tho
and it doesn't print?
main.py:22: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
meme = discord.Embed(title=f"{data['title']}", Color = 0xff0000()).set_image(url=f"{data['url']}")
do i need? to share the code
color = 0xff0000
yea
no ()
hm, shouldn't be
@slate swan here?
maybe color not Color ?
main.py:22: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
meme = discord.Embed(title=f"{data['title']}", color = 0xafc4ee()).set_image(url=f"{data['url']}")
the code is
@bot.command(aliases=['Meme'])
async def meme(ctx):
content = get("https://meme-api.herokuapp.com/gimme").text
data = json.loads(content)
meme = discord.Embed(title=f"{data['title']}", color = 0xafc4ee()).set_image(url=f"{data['url']}")
await ctx.send(embed=meme)
check the code below
you didn't remove the ()
ohk
why is it not adding the role lol maybe it cant get the role?
that only needs guilds intents and that's enabled by default
check if it's the right id
File "main.py", line 23
await ctx.send(embed=meme)
^
SyntaxError: invalid syntax
ξΊ§
probably didn't close a bracket
its this code
oh yeah
i deleted more by accident
thanks
try:
keyword = sys.argv[1]
except:
raise Exception('typing keyword. ex) python ./search.py aaaa')
execute(keyword)
def loginbot():
prefix = '!'
intents = discord.Intents.all()
client = commands.Bot(command_prefix=prefix, intents = intents)
@client.command(name = keyword)
async def _Search(ctx):
main()
with open('token.txt', 'r') as f:
token = f.read()
client.run(token)
if __name__ == "__main__":
loginbot()```
```TypeError: Name of a command must be a string.```
It's a program that searches.
What does this error mean and how do I fix it?
i wonder what does "Name of a command must be a string" means
execute(keyword)
def loginbot():
prefix = '!'
intents = discord.Intents.all()
client = commands.Bot(command_prefix=prefix, intents = intents)
@client.command(name = "ff")
async def _Search(ctx):
main()
with open('token.txt', 'r') as f:
token = f.read()
client.run(token)
i changed it but search name should be "ff" but "<class 'ast.keyword'>" this sentence is being searched
is there a variable for the prefix ?
thats the command name ποΈ
you need to use a command argument
you mean the bot's prefix?
await get_prefix(message, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the prefix the bot is listening to with the message as a context.
Changed in version 2.0: `message` parameter is now positional-only.
File "main.py", line 128, in kick
await member.send("You have been kicked from {member.guild.name} reason: {reason}")
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/abc.py", line 1013, in send
channel = await self._get_channel()
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/member.py", line 299, in _get_channel
ch = await self.create_dm()
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/member.py", line 142, in general
return await getattr(self._user, x)(*args, **kwargs)
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/user.py", line 764, in create_dm
data = await state.http.start_private_message(self.id)
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user
Traceback (most recent call last):
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user
i got this error when using the kick command
this is my code:
@bot.command(aliases=['Kick'])
@commands.has_permissions(kick_members = True)
async def kick(ctx,member : discord.Member, *, reason= "No reason was provided"):
await member.send("You have been kicked from {member.guild.name} reason: {reason}")
await member.kick(reason=reason)
Handle it with try-except
wdym
fyi you can pass in case_insensitive=True in your bot's constructor without the need of having an alias like that
Can a discode bot send only messages without a command?
What should I do if I can?
Yeah you only need channel id, with it you can get a channel object and send anything you want
channel = bot.get_channel(id)
await channel.send(...)```
ok thanks
but i prefer to use aliases
class MyHelpCommand(commands.MinimalHelpCommand):
def get_command_signature(self, command):
return f"{self.context.clean_prefix}{command.qualified_name} {command.signature}"
async def _cog_select_options(self) -> list[discord.SelectOption]:
options: list[discord.SelectOption] = []
options.append(discord.SelectOption(
label="Home",
emoji="π ",
description="Go back to the main menu.",
))
for cog, command_set in self.get_bot_mapping().items():
filtered = await self.filter_commands(command_set, sort=True)
if not filtered:
continue
emoji = getattr(cog, "COG_EMOJI", None)
options.append(discord.SelectOption(
label=cog.qualified_name if cog else "No Category",
emoji=cog.emoji, #<----------------
description=cog.description[:100] if cog and cog.description else None
))
in another file...
class Useful(commands.Cog):
"""Lots Of Useful Commands."""
COG_EMOJI = "π§°"
def __init__(self, client):
self.client = client
self.expr = ""
self.emoji = "π§°" #<----------------------
how would i put the emoji next to the dropdown menu? how do i access self.emoji?
async def send_msg(channel : channelid):
await channel.send('search rank[{}] server[{}]'.format(rank, title))```
Discord bot doesn't send messages to channel What's the problem?
i think you have to remove channelid from the command parameter
and you didn't declare the channel to send the message in
could not understand
could someone help pls!
The error says it, the member has their DMs closed
how to use
if "..." in "string" ?
Can we have more than one owner for a bot
how you showed
OK
!e py if "s" in "string": print("true") else: print("false")
@silk fulcrum :white_check_mark: Your 3.11 eval job has completed with return code 0.
true
can someone please help me?
if "<@&632317308035137578>" in message.content
?
is this right ?
it's better to use message.mentions
yes , by sharing it on a team
!d discord.Message.mentions
oh ok
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
what is the attribute to show description of user in whois command
?
like the about me
i think thats not possible

the user info 
Is there a way to batch mute a list of users in one API call rather than each individually?

There's no bulk member edit endpoint
Understood. Thanks! Just wanted to optimize calls required, maybe what I can do is just do Asyncio.gather since it would be faster I'd expect than simple iteration
API doesn't provide that either yeah
Depends on amount of users you are going to bulk edit, if it's huge it would be better to iterate not to get ratelimited
But iteration on a large number of users will be very slow... Hmm, I guess this is something to consider, good callout Evenifix!
I think I will need a restriction on users in a given channel to minimize concurrent edits
Since if on many many servers with many many users each that can be loooots of requests
why would you want the timeout on a large number of users, seems improper
It is for freestyle rap, I am building a module to automatically mute and unmute users depending on the cipher rotation
It is an automatic Cipher moderation tool which provides a valuable service to our Niche community
Since in very large servers it can very easily get quite chaotic so the intent is to automate the process of taming the ciphers so that server owners can more easily host events
And automating it 24/7 means that people can expect that anytime they log on ciphers will be orderly and clean
Hope that sufficiently answers your question
@ebon island If you really wanted to lower the number of API calls you make, you could change the Speak permission on the voice channel to False, which will by default mute anyone who joins it. Then just mute and unmute a single person using the API at a time.
I like that idea! Is that muting suppression or just regular mute? Meaning is it the red mute or gray mute?
gray mute, but they cannot unmute themselves unless someone with the Mute Members permission does it for them
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: asyncio.run() cannot be called from a running event loop
fix ??
Otherwise I might consider using stages as the basis because that way users are automatically not coming in as speakers and must opt in in order to participate
async def load2():
for filename in os.listdir('./commands'):
if filename.endswith('.py'):
await client.reload_extension( f'commands.{filename[:-3]}')
elif not filename.endswith('.py'):
filenametemp = filename
for filename in os.listdir(f'./commands/{filenametemp}'):
if filename.endswith('.py'):
await client.reload_extension(f'commands.{filenametemp}.{filename[:-3]}')
@client.command()
@commands.is_owner()
async def reload1(ctx):
asyncio.run(load2())
await ctx.send("done")```
I have not used stages that much but I imagine it would do something similar to what is intended anyway and we would not have to worry as much about the number of API calls because my main worry about the number is from additional people who would just be listeners who would need to be muted and unmuted as well whereas if it is just participants I think that number will stay manageable and the number of API requests will not become as much of an issue as ultimately we can limit the number of active participants at any one given time
I am not sure on that but I assumed they would be similar in operation to regular voice channels but I suppose that is something that I need to look into as well, good call out!
No need to use asyncio.run() here, just use await
await load2()
get the current running loop asyncio.get_event_loop and use the run_in_executor method instead of using run 'cause no
oh got it
blocking for loop 
your user has default discord avatar (no custom avatar)
you can check if user.avatar is None and then not use .url attr
Versuch einfach nur user.avatar, sollte auch funktionieren
@slate swan Machst du einen AV Command? Wenn ja wΓΌrde ich das anders machen
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?
@bot.slash_command(guild_ids = [979159861197688963], description = "test")
async def test(ctx):
await ctx.respond("Worked!")
just do await load2()
!d disnake.ext.commands.Bot.slash_command
@slash_command(*args, **kwargs)```
A shortcut decorator that invokes [`slash_command()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.slash_command "disnake.ext.commands.slash_command") and adds it to the internal command list.
dpy don't have it
yes, the import isn't working sir
thanks
heβs talking about a 3rd party module
so which one
i can't read minds
discord_slash π
just use disnake π

why:(
dpy has slash commands
π
!d discord.app_commands.AppCommand
class discord.app_commands.AppCommand```
Represents a application command.
In common parlance this is referred to as a βSlash Commandβ or a βContext Menu Commandβ.
New in version 2.0...
also this
hi
hi
i an new
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
dont get it
click the link
done that
select difdiculty and type on left
done
@commands.command()
async def gallery(self, ctx):
PreviousButton = nextcord.ui.Button(emoji='β¬
οΈ')
NextButton = nextcord.ui.Button(emoji='β‘οΈ')
await paginator.simple(PreviousButton=PreviousButton,
NextButton=NextButton,).start(ctx, pages=embed)
``` could someone help me use paginator? it throws the same error whether its Simple or simple even though i thought i was following the documentation https://github.com/soosBot-com/Pagination
Can someone help me?I don't know how to send generated link to webhook
This is my code
a
how are you importing paginator into your file?
i have import paginator at the top of the cog file
i get the same error if i use paginator.Simple
the example on GitHub says import Paginator
if i do import Paginator, it says "No module named Paginator"
install it
Doing pip list do you see paginator among the modules?
yes i do, i also just ran pip install Paginator and it says it was already installed
it's pip install discord.py-pagination
would i do that even if im using Nextcord ?
i have a venv with pycord installed in it, it shows pycord in pip freeze, but when i run it, it just says "no module named discord"
I think so
in theory nextcord is a fork of Discord.py, it should have the ui kit
you will have problems with the module probably, install also Discord.py
or copy the code and change it for your case
i got it to work! thank you so much for the help
you're welcome
like i can import flask fine but not pycord
are you getting any errors?
also I noticed that you are using ctx but it is not defined in your function
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
What library are most people using instead of discord py?
I've been looking at disnake but not sure if there's a more popular one that people can recommend
Why instead of discord.py?
if you want the function names and code structure to be similar to that of dpy, disnake is the most recommended
if you are looking for a completely different api wrapper, then hikari ftw
When I last looked discord py wasn't being supported anymore? π€
It is now! It's got all of the new features if you're on 2.0 (slash commands, buttons, dropdowns, modals, and much more)
Oh really??
Ah okay thanks, I was thinking of going with disnake because it seemed similar
Oh that's great, saves me a lot of hassle then, I'll just take a look over it and see what's changed
@client.command()
@commands.has_role('General Officer')
async def mute(ctx, member: discord.Member):
mutedRole = discord.utils.get(ctx.guild.roles, name="Muted")
await member.add_roles(mutedRole)
await member.send(f"You have been temporarily muted in **{ctx.guild.name}** by user: **{ctx.author}**.")
channel = 999759936122794017
embed = discord.Embed(
title = "Moderation Notice",
description = f"{ctx.author} has executed the command: **MUTE** on {member}.",
color = 0xe74c3c #RED
)
embed.set_footer(text = f"ID - {member.id}")
await ctx.send(embed = embed)
await channel.send(embed = embed)
This performs ctx.send but does not with channel.send. Any ideas as to why this is happening?
int doesn't have a .send method
you should use guild.get_channel instead
Ohh okay.
Could you show me an example?
get_channel(channel_id, /)```
Returns a channel with the given ID.
Note
This does *not* search for threads.
Changed in version 2.0: `channel_id` parameter is now positional-only.
you call this on a Guild object like ctx.guild
subclass discord.Client or whatever you're using and annotate command_list
is that an error or your linter's warning?
linter warning prolly
if you want custom attributes (AKA variables) for bot, then you need to subclass Bot class and add them into __init__ method or use classvars
yeah subclassing would be the deal then
you don't need to add them to _init_
except for the init you can use classvars too
class MyClient(Client):
attr = {}
``` will do
What is the simplest way to do embed pagintion?
yes, but why do you even need that for a class variable
!d discord.ext.commands.Paginator probably
class discord.ext.commands.Paginator(prefix='```', suffix='```', max_size=2000, linesep='\n')```
A class that aids in paginating code blocks for Discord messages.
len(x) Returns the total number of characters in the paginator.
hmm or not
Wdym?
@torn spear maybe this would be better https://github.com/soosBot-com/Pagination/
okay
create your own paginator class,
add list of embeds as an attribute for the class
add an index attribute to the class with beginning value as 0
on each button/reaction click change the index to +1 or -1 and edit the message accordingly using that list attribute with embeds
that's not the simpliest way..
you can use the init dunder and define the command_list attribute there, but why there when you can use class variables?
await Paginator.Simple().start(ctx, pages=embeds)```
How would this look in discord.py v2?
Would I just need to replace ctx with interaction?
why would you have interaction instead of ctx?
is that a slash command?
Yes
does anyone know if i have to use a database for a mute command now or what since if a member already has a role that lets them able to talk the muted role has no affect even regardless of the role hierarchy i made it where when i mute the member it takes all the roles away which works but when the time runs out or they get unmuted the member cant get their roles back anyone know how to deal with this?
you have to get ctx from interaction, this can be done via await commands.Context.from_interaction(interaction)
class Paginator:
embeds: list[Embed]
index = 0
message: Message
async def next_page(self,):
self.index += 1
await message.edit(embed = self.embeds[index]
async def prev_page(self):
self.index -= 1
await message.edit(embed=embed(self.index)
@command()
async def foo(ctx):
embeds = [...]
pag = Paginator()
pag.embeds = embeds
pag.message = await ctx.send/reply(embed=embeds[0])
# add emojis
try:
while True:
event = await bot.wait_for...
# check emoji
await pag.next_page() # for next page
await pag.prev_page() # for previous page
except TimeoutError:
...
i typed it all on a phone so
YOU typed it all on a phone so
uhm well you can just save member.roles and then give them back, like py ... backup_roles = member.roles await member.remove_roles(backup_roles) await asyncio.sleep(mute_time) await member.add_roles(backup_roles)
What does that do exactly?
gets Context object from Interaction one
!d discord.ext.commands.Context.from_interaction
classmethod await from_interaction(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a context from a [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). This only works on application command based interactions, such as slash commands or context menus.
On slash command based interactions this creates a synthetic [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") that points to an ephemeral message that the command invoker has executed. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the member that invoked the command.
In a message context menu based interaction, the [`Context.message`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.message "discord.ext.commands.Context.message") attribute is the message that the command is being executed on. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the author of the message being targetted. To get the member that invoked the command then [`discord.Interaction.user`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.user "discord.Interaction.user") should be used instead.
New in version 2.0.
Okay
tf this is cursed
thanks but what if i want to unmute then without waiting for the mute time to expire would it be a similar function
ohhh
use timeouts and you can remove the timeout anytime you want to
yeah gotta learn how to use thoes
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
PageCounterStyle = discord.ButtonStyle()```
Does `discord.ButtonStyle()` take any arguments?
Would this look like:
await commands.Context.from_interaction(interaction)
await Paginator.Simple()```
The pagination goes straight after?
!d discord.ButtonStyle
class discord.ButtonStyle```
Represents the style of the button component.
New in version 2.0.
It isn't a function
Resolved.
@bot.command()
async def priavtedm(ctx):
if ctx.channel.id==998928038047780935 or ctx.channel.id==1004484809848016966:
emb3=discord.Embed()
emb3=discord.Embed(title="private dm sentβ
",description=f"Check your inbox {ctx.author} !",color=0xffff00)
await ctx.reply(embed=emb3)
embed2=discord.Embed(title="test",description="pv dm",color=0xffff00)
embed2.add_field(name="Generated info:",value=random.choie(privatedm))
await ctx.author.send(embed=embed2)
First await ctx sends the last one doesn't im not sure why
why when i say the key word hint help it still says zero when it tells you who said yes and no
Last one sends it into dm
Show the whole function
ok
Yes ik but its not sending
async def on_message(message):
user_message = str(message.content)
word = ["hello", "money", "bot"]
rng = random.choice(word)
if message.author == client.user:
return
if message.content.startswith("%start"):
print(rng)
if message.content.startswith(rng):
await message.channel.send("Congrats you found the word, the word was " + rng)
if user_message == "%hint":
await message.channel.send("Poll time, want a hint? say 'hint yes'if you want a hint, say 'hint no' if you dont want a hint you have 1 minute to decide")
yes = 0
no = 0
if user_message == "hint yes":
yes += 1
if user_message == "hint no":
no += 1
for i in range(5, 0, -1):
print(i)
time.sleep(1)
if i == 1:
await message.channel.send("Times up! The amount of people who said yes is " + str(yes) + " the amount of people who said no is " + str(no))
client.run(token)
So basically every time someone sends a message yes and no variables will reset
Print out embed
print(embed2)
Alr
Don't use time.sleep
Yes I wanna see what it prints
Nope
Wdym
Then embed is the issue here
Well i cant seem to find the issue
..
random.choie
Can u send a ss so I can read code easier
Ill just send it all
U got a point
Iβ m on mobile so I can read from screenshots best
@bot.command()
async def priavtedm(ctx):
if ctx.channel.id==998928038047780935 or ctx.channel.id==1004484809848016966:
emb3=discord.Embed()
emb3=discord.Embed(title="private dm sentβ
",description=f"Check your inbox {ctx.author} !",color=0xffff00)
await ctx.reply(embed=emb3)
embed2=discord.Embed(title="test",description="pv dm",color=0xffff00)
embed2.add_field(name="Generated info:",value=random.choice(privatedm))
await ctx.author.send(embed=embed2)β
thats just it nothing else.
Ye but Itβ s indented weird on my phone
You on pydroid?
Iβ m on my phone rn π
Would also show indent error
how can i fix
Ik Itβ s indented right but for me Itβ s weird so Itβ s hard to read
Send a screenshot π
same
Ohh okok
Pydroid 
Where is privatedm defined
i think emb2 needs defining
how can i fix
Thats the error
You store it either in db or in ram somewhere outside that function
Nawh not the issue
Like class variable or whatever
@lone lichen
Yes?
Can u send the code u have rn
How to read the .txt file which the user sent?
!d discord.Message.attachments
A list of attachments given to a message. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
This may help
also, is there a tutorial for web scraping?
There is many
what's the good one?
Idk probably the docs from whatever library ur using
@bot.command()
async def priavtedm(ctx):
if ctx.channel.id==998928038047780935 or ctx.channel.id==1004484809848016966:
emb3=discord.Embed()
emb3=discord.Embed(title="private dm sentβ
",description=f"Check your inbox {ctx.author} !",color=0xffff00)
await ctx.reply(embed=emb3)
embed2=discord.Embed(title="test",description="pv dm",color=0xffff00)
embed2.add_field(name="Generated info:",value=random.choice(privatedm))
await ctx.author.send(embed=embed2)ββ
Still not working
Where is privatedm defined
?
i havent defined inline
You put a string inside random.choice?
Does that work?
no...
@cold tide Can you come in private for a sec?
Yes but there is privatedm inside, what is that
The variable which it will random.choice
Yes but what type is it
You can lol trust me
do privatedm = [βtestβ]
it would of shown syntax errors
@lone lichen that didnt work
What didnt work
putting the variables in a class
Show code
What does it return?
Wym?
It wont show syntax error for that
random.choice(βtestβ)
No...
!e
import random
print(random.choice("test"))
@pale turtle :white_check_mark: Your 3.11 eval job has completed with return code 0.
t
privatedm="test"
random.choice(privatedm)
#thats what it does
import time
class vars():
yes = 0
no = 0
client = discord.Client()
@client.event
async def on_message(message):
user_message = str(message.content)
word = ["hello", "money", "bot"]
rng = random.choice(word)
if message.author == client.user:
return
if message.content.startswith("%start"):
print(rng)
if message.content.startswith(rng):
await message.channel.send("Congrats you found the word, the word was " + rng)
if user_message == "%hint":
await message.channel.send("Poll time, want a hint? say 'hint yes'if you want a hint, say 'hint no' if you dont want a hint you have 1 minute to decide")
if user_message == "hint yes":
yes += 1
if user_message == "hint no":
no += 1
for i in range(5, 0, -1):
print(i)
time.sleep(1)
if i == 1:
await message.channel.send("Times up! The amount of people who said yes is " + str(yes) + " the amount of people who said no is " + str(no))
client.run(token)
So Itβ s random char from string?
@lone lichen
@lone lichen
@cold tide I don't know if what I am saying is even correct, but maybe it mistakens the privatedm for the command function, not the variable. Try to call the variable something else maybe
Is variable global?
Ur class vars is unused, nothing has changed
i dont know much ab classes
If you define a variable in on message it will redefine every time a message is sent
where can i put it
I have
Outside of on_message
That would make it global which is not rly the best way, depends on ur use case u could have a db or json or something
i got a ereor
Try to just send value=βhello worldβ for testing
Which
Still doesn't work? Did you change the var in the random.choice and the global var?
So u deleted yes = 0 and no = 0?
no
import discord
import random
from discord.ext import commands
import time
yes = 0
no = 0
token =
client = discord.Client()
@client.event
async def on_message(message):
user_message = str(message.content)
word = ["hello", "money", "bot"]
rng = random.choice(word)
if message.author == client.user:
return
if message.content.startswith("%start"):
print(rng)
if message.content.startswith(rng):
await message.channel.send("Congrats you found the word, the word was " + rng)
if user_message == "%hint":
await message.channel.send("Poll time, want a hint? say 'hint yes'if you want a hint, say 'hint no' if you dont want a hint you have 1 minute to decide")
if user_message == "hint yes":
yes += 1
if user_message == "hint no":
no += 1
for i in range(5, 0, -1):
print(i)
time.sleep(1)
if i == 1:
await message.channel.send("Times up! The amount of people who said yes is " + str(yes) + " the amount of people who said no is " + str(no))
client.run(token)
I think with 2.0 they changed some methods so they only accept positional arguments
How to fix??
@lone lichen
Okay so I just read ur whole code and I think I have an idea of what ur trying to do and I see a couple of issues
@lone lichen the issue is you cant use random.choice function in a test=discord.Embed(title)
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.10)"). 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.10)") 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.10)") 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**...
@lone lichen can we go dms??
@golden tapir take a look at this
Sure
It may just be my phone but it looks like u indented it wrong
to be looken at
This
Accept me @lone lichen
ik
I did
but where
Click in it and read what it does
Then try to think how it would help u
Click the blue hyperlink
Do you know what wait_for does?
no
U didnt read it then
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.
well
i want to wait 5 sedonds for people to vote yes or no to a hint
and when done
i want it to say howmany peole said yes and howmany peo;le say no
so @lone lichen what should i do?
So basically u wanna send something and then wait 5 seconds for multiple people to vote on it?
You can do that with reactions easily
Then just wait five seconds, and get all messages between now and five seconds ago and see how many of them are hint yes and how many of them are hint no
ig
no
the bot waits 60
and eveytime some one says hint yes or hint no
it adds one point to the right var
so peole know who won
It can wait 5 sec or 60 sec or 100 years
You can just wait x amount of seconds and afterwards check how many yeses and nos u got
yes
but
when ge prints how many peole said yes and no
he just prints 0
for both
Id just do it this way
what the correct indet
Why? who is know?
Code:
@reset.command()
async def role(ctx, role:nextcord.Role=None):
with open("messages.json", "r") as f:
user = json.load(f)
if role == None:
embed=nextcord.Embed(title="Error!", description=f"You did not use the command correctly.\nPlease be sure to use `!reset-messages role [@role/id/name]`", color=0xff0000)
await ctx.send(embed=embed)
return
roles = nextcord.utils.find(lambda r: r.name == role.name, ctx.guild.roles)
for i in roles:
del user[str(i.id)]
new = json.dumps(user, indent=4)
with open("messages.json", "w") as write_file:
write_file.write(new)
embed=nextcord.Embed(description=f"**All messages reset for `{role.name}`**", color=0x00ff1e)
embed.set_author(name="Done!",icon_url="https://images-ext-1.discordapp.net/external/vhSiwNAMWMj7Bl6Dpsz6nUzUQO-9E4EIp7TsIs5wBQw/%3Fv%3D1/https/cdn.discordapp.com/emojis/788751803743338506.gif")
await ctx.send(embed=embed)```
roles is one role, u cant iterate through it
oh ok
The hint yes and no if statements will only have effect if they are outside hint if statement
and its?
What are u trying to do?
why am i getting spamed this
Go through each member that has the role
for member in guild.members:
if role in member.roles:
Kaboom
Just do what I told u
Do this
i litterly cant run it
I wouldnt use replit
ok
Yes Itβ s replit issue
working! thank you man!
Np
Is there more to error?
guild_ids should be a list
Since u made a function to fet the ids u should call it
ids()
And it would help if ids function returned a list of ids
Now it returns void
No
It must be a list
guild_ids=ids()
He made a function that is supposed to return a list of ids
And also check that you have activated the slash command in the bot's Api
But it doesnt return ids cus he didnβt implement that
@slate swan your ids function must return list of ids
What do u want ids to get?
Rn it gets the row for one guild
Where do u have stored ids that u want to have in guild_ids
Get it from there
And you dont need interaction parameter in ids function
Depends on how u stored it
If you have a table with all guilds you should probably just get all ids
Select id from guilds
And now u got all guild ids
^
Yes probably, depends on what library ur using
And return the result
How many Discord.py forks are there? I am not looking for an exact number. I am looking for an estimate.
I know for 3 or 4 but there could be much more
I know 2 forks.
I used Pycord a little bit.
Like u can fork it rn if u want and there will be one more
So, I've been looking into discord.ext.commands.Bot, trying to put it into a custom class to so it contains state, but it seems like using the commands.Bot extension is more for 'static' commands? Can provide code if this isnt clear
You can subclass it and use super in constructor
Then u can overwrite events etc.
Just like any other subclassing
commented stuff cant figure out how to do
import os
import discord
from discord.ext import tasks, commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
class CustomBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.members = True
intents.messages = True
super().__init__(command_prefix='!', intents)
self.important_info = 2
async def on_ready(self):
print(f'{self.user} has connected to Discord!')
# this doesnt work, does not get set as a command
#async def test(ctx):
# await ctx.send(important_info)
bot = CustomBot()
@bot.command()
async def test(ctx):
#cant do this
#await ctx.send(important_info)
pass
bot.run(TOKEN)
I can do it as a discord.Client though using on_message event
Use cogs
mmm k I'll look into those
I used pycord a little bit. I never heard of disnake.
I love em
It's interesting.
I highly suggest
Just another fork
ah yeah that'll probably work
Mhm
And it will be way more organised
@slate swan any luck with ur problem?
Did u change anything?
Show me
Yes Itβ s because ids doesnβt return anything
Print cursor.fetchall() first
So you see if ur on the right path
Did u make it return the result?
Ok great
Glad it works now
mmm doing something wrong, looks good by documentation...
import os
import discord
from discord.ext import tasks, commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
class CustomCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.important_info = 2
@commands.command()
async def test(ctx):
await ctx.send(important_info)
intents = discord.Intents.default()
intents.members = True
intents.messages = True
bot = commands.Bot(command_prefix="!", intents=intents)
bot.add_cog(CustomCog)
bot.run(TOKEN)
TypeError: cogs must derive from Cog
dont think cogs have an on active
CustomCog(bot)
ah
you need an instance, not a class
@commands.cooldown(1,10,commands.BucketType.user)
@bot.command()
async def test(ctx):
sent_message = await ctx.channel.send("Waiting for response...")
res = await bot.wait_for(
"message",
check=lambda x: x.channel.id == ctx.channel.id
and ctx.author.id == x.author.id
and x.content.lower() == "x",
timeout=10,
)
if res.content == "x":
await message.reply(".")
@calis.error
async def calis_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.reply('Wait `{e:.1f}` sec.'.format(e = error.retry_after))
elif isinstance(error, commands.CommandInvokeError):
await sent_message.delete() < #IT'S NOT WORKING```
how can i make the bot delete sent_message?
im working on it for 1.5 hours
and still cant find the solution
can somebody help me please?
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.10)") 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.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
btw theres a delete_after kwarg
damn thats true
i didnt think it
thank you so much
async def withdraw(self, ctx, amount: int , all:str = None):
how can i make command which accsept int + all string ??
amount, *, all?
the Asterix means everything after, consider as part of that 1 var regardless of spaces
oh, add default val for amount too then?
discord.py allows using typing.Optional to specify optional arguments in the middle
why does my bot say there is 0 peole who said yes even tho i said yes
client = discord.Client()
@client.event
async def on_message(message):
user_message = str(message.content)
word = ["hello", "money", "bot"]
rng = random.choice(word)
if message.author == client.user:
return
if message.content.startswith("%start"):
print(rng)
if message.content.startswith(rng):
await message.channel.send("Congrats you found the word, the word was " + rng)
yes = 0
no = 0
if user_message == "%hint":
await message.channel.send("Poll time, want a hint? say 'hint yes'if you want a hint, say 'hint no' if you dont want a hint you have 1 minute to decide")
if user_message == "yes":
yes += 1
if user_message == "no":
no += 1
for i in range(5, 0, -1):
print(i)
time.sleep(1)
if i == 1:
await message.channel.send("Times up! The amount of people who said yes is " + str(yes) + " the amount of people who said no is " + str(no))
client.run(token)
intents, most likely
use commands.Bot instead of discord.Client and enable all intents via bot = commands.Bot(..., intents=discord.Intents.all())
and also enable them on dev portal
your logic needs to be rewritten to work asynchronously
In bot you can upgrade to @bot.command(), but if you want to stay with that if trash then sure, bot won't affect it
will it fix my problem?
also this doesn't work
yes
ok
Why isn't there any pin about intents, maybe I should make one
but isnt I lazy?
considering they said their bot got to the point where it said how many answered at all means their on_message event was firing normally
and using @bot.command() is a good idea, but it doesnt influence how you'd write the logic for this kind of command
code pls
you'll need another listener or a wait_for to handle receiving messages in the chat until your timeout
why am I so sure he didn't change client to bot somewhere
bot = commands.Bot(command_prefix="%", intents=discord.Intents.all())
@bot.listen()
async def on_message(message):
user_message = str(message.content)
word = ["hello", "money", "bot"]
rng = random.choice(word)
if message.author == bot.user:
return
if message.content.startswith("%start"):
print(rng)
if message.content.startswith(rng):
await message.channel.send("Congrats you found the word, the word was " + rng)
yes = 0
no = 0
if user_message == "%hint":
await message.channel.send("Poll time, want a hint? say 'hint yes'if you want a hint, say 'hint no' if you dont want a hint you have 1 minute to decide")
if user_message == "yes":
yes += 1
if user_message == "no":
no += 1
for i in range(5, 0, -1):
print(i)
time.sleep(1)
if i == 1:
await message.channel.send("Times up! The amount of people who said yes is " + str(yes) + " the amount of people who said no is " + str(no))
bot.run(token)
why @bot.listen(), why not .event
well listen exists so I guess there is no problem with this
oh wait you're about this ?
yes
trying to set up timeouts but i keep getting a AttributeError: 'Member' object has no attribute 'timeout' but i cant see where im going wrong
@commands.command()
@commands.has_permissions(kick_members=True)
async def mute(self, ctx, member: discord.Member, *, time:str, reason=None):
time_in_seconds = humanfriendly.parse_timespan(time)
await member.timeout(until = datetime.timedelta(seconds=time_in_seconds), reason=None)
await ctx.send("timed out")```
is ctx.message a thing
yes
like is there a way to check user message using ctx?
but don't overuse it
wdym
didnt solve my problem idk why
ctx.message.content
still attribute error?
yep
do pip show discord.py to make sure you use dpy2.0
why doesnt it work
im on ver 1.7.3 lemme upgrade rq
you are trying to do the same thing using ctx.message.content and check if it is your word, it won't be it, at least because ctx.message.content will start with %start
you need to use argument or wait_for
what?
ctx.message represents message with execution of command
so this will be ctx.message.content: !start
or whatever prefix you have
ah
i have to await cogs?
you can use argument to check if it is your word (so user would type !guess [word] and bot will check if [word] is the random word), or use wait_for
here are examples for args: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html#parameters
here are examples for wait_for: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for
almost
you can't wait_for some word
no
you need to pass type (message) into wait_for
i am waiting for the variable
wait_for('message')
i am confused
and to wait for certain thing you need to pass check
i am waiting for the user to send
how to use checks must be in examples I provided
import os
import asyncio
## - Bot - ##
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='.')
#ClientToken = '-/-'
ClientChannel = -/-
@client.event
async def on_ready():
print('Bot is online. Posting message..')
channel = client.get_channel(ClientChannel)
await channel.send('test.')
client.run('-/-')
is there anything wrong with this
yeah
there is, if you are using dpy 2.0 or ClientChannel is not valid id
its something wrong with client.run()
also don't name commands.Bot instance client
if the invalid token passed, then yes
: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')]
try it and see?
always something with mac
how can i stop defould help command
!d discord.ext.commands.Bot.remove_command
remove_command(name, /)```
Remove a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.
This could also be used as a way to remove aliases.
Changed in version 2.0: `name` parameter is now positional-only.
@limber bison also this is better as a help command #discord-bots message
so i just upgraded my python version now im getting "'BotBase.load_extension' was never awaited discord.py"
how do i await it
Ye it has changed on dpy 2.0
async def setup(bot):
await bot.add_cog(CogName(bot))```
i also need to add that in each cog?
ye it has to be async
yes
ok
ok
@bot.slash_command(description='Activate your token.')
@commands.has_permissions(administrator = True)
async def nitrado(interaction : Interaction, token : str = SlashOption(description='Enter your token here!')):
I was checking into how to make a command locked to a certain perm, am I doing something wrong here by chance? I had a friend test it, it didn't work.
what library are you using
looks valid, I'm not really familiar with pycord slash commands, more dpy but seems absolutely fine, so what does not work?
pycord, 100%
ok
I'm looking at it, not sure what I'm missing lol
I'm not sure if there's an import I'm missing or what, I truly can't find it. Lol
so is there an error? or what?
try
I'm sorry for wasting your time, my friend is just dumb
nextcord.ext.application_checks
It works. Lol Thank you though π
no, me is
No, u smart
no me stupid
well
or just check permissions yourself
Yeah, I should've. I figured my buddy could handle it
I was wrong 
well, that's most likely problem with ur db, you're getting no id or wrong id, which can't be found. or probably the channel was deleted
try printing rows to see what you get
this doesn't look like you printed rows
put print(rows) here
below this line
int(tc)
id=int(tc)
i did this all still now working
error?
vc = guild.get_channel(info["vcid"])
vc.set_permissions(member , connect=True)
error : 'NoneType' object has no attribute 'set_permissions'
info["vcid "] its id of vc from database
@bot.slash_command(description='Activate your token.')
@application_checks.has_role('Obelisk Perm')
async def nitrado(interaction : Interaction, token : str = SlashOption(description='Enter your token here!')):
try:
embed = nextcord.Embed(
title="`Nitrado Obelisk`",
description=f"`π’` `> System Success` \nYour token has been registered!\nResponse: `({token})`", color=3066993
)
clientGuildId = str(interaction.guild.id)
db.collection('nitrado').document(clientGuildId).set({'token' : token})
await interaction.response.send_message(embed=embed, ephemeral=True)
Can anyone by chance help with this? For the @application_checks.has_role('Obelisk Perm') if a user does not have the permission, it will simply reply with "Failed To Respond" how would I go about error handling this with a response if it's a slash command?
its probably a string, try int(info["vcid"])
await bot.load_extension("utility")
await bot.load_extension("reactions")
await bot.load_extension("help")
await bot.load_extension("moderation")
await bot.load_extension("fun")```
thats what i was supposed to do correct?
idk, i dont see your whole code so cant understand whats the problem
async def setup(bot):
await bot.add_cog(utility(bot))```
if these are files named like this and in the same folder then yes
then did tha for all the cogs
is there something more i need to do?
i see some things online but idk they dont seem to work either
simple error handler
@bot.event
async def on_command_error
where did you put those
ill show u the whole like main page
from distutils.log import error
import os
import discord
import asyncio
from dotenv import load_dotenv
from discord.ext import commands
from help import MyHelpCommand
load_dotenv()
token = os.getenv("BOT_TOKEN")
intents= discord.Intents.default()
intents.members = True
intents.presences = True
intents.messages = True
intents.reactions =True
bot = commands.Bot(command_prefix = ",", intents=intents)
bot.help_command=MyHelpCommand()
bot.reaction_roles = []
@bot.event
async def on_ready():
print("Your bot has successfully connected!")
await bot.load_extension("utility")
await bot.load_extension("reactions")
await bot.load_extension("help")
await bot.load_extension("moderation")
await bot.load_extension("fun")
bot.run(token)```
Thank you, never messed with the application checks, thought there were different π
lists do not work like that, dicts to
!e py xplvlratio = {1: '100', 2: '255', 3: '475'} print(xplvlratio[3])
@silk fulcrum :white_check_mark: Your 3.11 eval job has completed with return code 0.
475
@slate swan ^
..why
async def hello(self , ctx , amount : typing.optional[int] , all : str = None)
Why this giving error when I type , ?hello all
is it giving a TypeError or a ValueError
^
Yup boss , working when I initialise amount
But i don't want to initialise it
so when you have two optional arguments in a discord command, it will always assign the value to the first one
Optional
my suggestion would be to accept an optional string argument and inside your command try casting it to an integer. like ```py
@commands.command()
async def hello(self, ctx, arg: str = None):
try:
arg = int(arg)
# The argument passed is for an amount
except ValueError:
# The argument passed is for a string
also why would you do Optional for one argument and for second = None
It's work like ,
Case 1 ,
!deposit 50
Case 2 ,
!deposit all
you didn't get me...
Casino bot !!!
my suggestion would work great for that
you would need to modify the try/except for something like ```py
try:
amount = int(arg)
except ValueError:
if arg == 'all':
amount = # Query for the amount to use
give them amount
Thanksssss buddy
you can always just use isinstance
if you are going to accept the argument initially as a string, then isinstance would always fail if it was an integer
well it depends if he does use an annotation
you have to attempt to typecast and handle the error if it fails
even if he doesn't use annotation it would still come in as string, no?
does* lol
If statements will be in try block right ? π€
Ohh got it nvm
Ignore
What's this?
modal?
Oh
Cool
Is it possible to edit an embed, without it saying "edited" in the bottom corner?
no
The entries changed here, but it doesn't say edited
what changed?
Entries: 0 -> Entries: 1
idk
probably the message was deleted and resended?
how do i make a slash command response private (that "only you can see" message thing)
i know how to do it normally interaction.response.send_message
ephemeral attr
*kwarg
oh its a kwarg
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
how do i change the bots pfp every 24 hours?
you should use a task loop
Ok, ill try to do it
How can I get this to return like 11+11 instead of what it currently returns, which is [1, 1]+[1, 1]
def generate_sum() -> str:
operation = choice(OPERATIONS)
start = choices(NUMBERS, k=2)
end = choices(NUMBERS, k=2)
return f"{start}{operation}{end}"
I tried the join method but it didn't help
what is NUMBERS?
why don't you just use random.randint instead?
that constant is a list of numbers from 1 to 9
if you just want to generate a random 2 digit number you can use randint
okay thanks
@client.command()
async def on_message(ctx, log):
channel = client.get_channel(1006552645730840630) #channel id here
await channel.send(log)
def checkServerPlayers(title, url, keyword):
query = keyword.lower()
doc = getDoc(url)
rows = doc.select('#serverPage tr > td > a')
for row in rows:
name = row.text.lower()
if query in name:
log = (
"name : {}\r\n"
"full name : {}\r\n"
"----------------------------------------\n"
)
bot_messages(log)
print(log.format(title, name))```
I want to automatically print out the name that the user wants to search for on the channel after writing the command. What method should I use?
!d discord.File
class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
Why are self bots against the discord tos?
Because they pretend to be a bot
I don't think that is possible
it's just not allowed don't do it
I wont, i was just asking
Ah
But a friend of mine uses self botting to automatically bump
No, bots sadly cant use slash commands :(
I think the reason they are against tos is because some of them send physhing links around and raid servers
If ppl were just using them to bump I think they wouldnt be
bots can use slash commands
self bots can't
or you mean use them like execute?
oo
Can someone link some resource on how create a discord.py cluster for HA? TLDR I want to deploy our bot in my Kubernetes cluster and run an instance on all nodes, but one event should only be processed once. How do I achieve that?
execute
i didn't mean trigger them
like disboard /bump
Thanks
Oh ok
is there something i did wrong in my code i use pycord
because the bot aint replying to me
sent your token
also uhm i reseted the token sooo uhh
ik
so did i do any mistake
seems, valid, any errors?
what are you typing?
hello
You may have to enable message content intents
oh yeah
Idk how to do that in pycord tho
what that/
also don't name commands.Bot instance client
wha- why?
the same as in dpy
(was checking docs to make sure)
discord.Client should be named client. commands.Bot should be named bot
^^
OHH OK
imagine pass_context π
= False π³
can someone send me the code of unban for python
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 the [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
thanks
- Your function is called
check_inputand you use it ascheckinputinstead - Consider not calling function in itself, that might cause infinite loop or other problems
- Instead use checks in wait_for function, examples you can find here: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for
If you read an example called "Waiting for a user reply:", you could see how check must look like:
def check(m):
return m.content == 'hello' and m.channel == channel```, so that is a function that receives a message object and returns True if custom conditions are met and False otherwise. In this example check function checks if the message was sent in a current channel (so it won't count messages from other channels) and if the message content is "hello". Note that check function should not be asynchronous (not `async def`). And in the wait_for you specify type and your check function. So let's make another example:
```py
def check_input(message):
return message.channel == ctx.channel and message.author == ctx.author
m = await bot.wait_for('message', check=check)``` In this example check function checks if message channel is current (ctx) channel and author is same
I did my best to explain what to do π
please what?:(
and then people are asking me why am I so rude lemao
idk, lemme check, you said so?
i though you are still not understanding what to do
oh you just copied my example...
spoiler: that was an example
error?
!paste also this
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
that's also to not spam the channel...
this way to get channel id looks not very good
but anyways you tell members how to mention it
hey any idea what i need to learn if i wan to create my own discord.py like library
also everything is french but this on english
a fork or own API wrapper?
own api wrapper
oh.. well I don't know much about it, you can ask @sarth#0460 or @okimii#0434 when they're online
oh ool
uhm.. seems valid, weird that it does not give any errors, it might be this #discord-bots message
you should know websockets for sure. also probably async
he should also know a lot about Object, Class, dunder methods etc...
These are links to get started with the discord api if u want https://discord.com/developers/docs/topics/gateway https://discord.com/developers/docs/reference
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
yeah
query = keyword.lower()
doc = getDoc(url)
rows = doc.select('tbody > tr > td > a')
for row in rows:
name = row.text.lower()
if query in name:
log = (
"name: {}\r\n"
"full name : {}\r\n"
"----------------------------------------\n"
)
print(log.format(title, name))
f.write(log.format(title, name))
async def on_message(message):
await message.channel.send(log)```
how to bot is send message without command
this is not working..
agree but for now websockets is the one i need
!d discord.Client.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
!d discord.TextChannel.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.10)") 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.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
Bump
Is there a way to send a message without using async?
in theory you could make your own call to the Discord api in a non-asynchronous way, but this is
very not recommended indeed, it should not be done if you are working in an asynchronous context like that of a normal Bot
But I don't think there's a way to send the message I want unless it's that way
explain what you want to do, there will be a way to do what you want to do
query = keyword.lower()
doc = getDoc(url)
rows = doc.select('tbody > tr > td > a')
for row in rows:
name = row.text.lower()
if query in name:
print(title, name)```
I want to send out the title and name as a message.
But I still don't know how to solve this
if i change that to async def check players (title, url, keyword): the next line will not run
do you get any errors when you turn the function into async def...?
hey
is there any problem with my code the buttons the >hello command with buttons dont work tho :(
@client.event
async def is_owner(message):
owners = ('283224945843109888')
if message.author.id == owners:
return owners
Are two IDs possible in a list? I tried and it doesn't work, can someone please solve this? Or can't it be solved?
If i use async def, there will be no value in the title, name
and error is RuntimeWarning: coroutine 'execute' was never awaited
print('===================================')
print('>> name : {}'.format(keyword))
print('===================================')
findKeyword(keyword)
print('>> end.')
async def findKeyword(keyword):
url = 'link'
for i in range(1, 2):
doc = getDoc(url)
checkServers(doc, keyword)
url = getNextUrl(doc) ```
You can use commands.is_owner (it's already a thing), it accepts a discord.User object I think
@bot.command()
async def online(ctx):
role = discord.utils.get(bot.get_guild(ctx.guild.id).roles, id ="940644669652631663")
await member.add_roles(role)
I've got an error, could anyone help?
!e x=range(1,2,2 )
for n in x:
print(n)
@supple dragon :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
!e x=range(1,2,5 )
for n in x:
print(n)
@supple dragon :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
!e @bot.command()
async def online(ctx):
role = discord.utils.get(bot.get_guild(ctx.guild.id).roles, id ="940644669652631663")
await member.add_roles(role)
!e x=range(1,10,5 )
for n in x:
print(n)
@supple dragon :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1
002 | 6
for getting a role with a particular ID from the current guild, consider using ctx.guild.get_role(<id>) instead
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
also note that the ID should be an integer instead of a string
Yeah, I tried that too, but I wanted to put more ID for few users.
Discord applications can be made a team where other users can be part of
commands.is_owner checks for these team members too
^ or alternatively you can specify the owner_ids= argument in your commands.Bot() constructor
Good to know
The channel for bots commands is #bot-commands, this one is for help creating discord bots
@supple dragon
How would i go about making a whitelist command? Something what will look a little bit like this: !whitelist @slate swan Bot: given the @slate swan role to @slate swan
ohh sorry, i just had a doubt so i was checking it
no problem haha
itd be similar to what you wrote before, only with the get_role() suggestion and adding a parameter to your command with a discord.Member typehint to handle mentions
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#discord-converters
there's a good chance even that returns None π and there's no endpoint for fetching a single role either
kinda hate that impl that even utils.get returns None even if all the roles are passed into the iterable
Hi Is anyone here good with discord.py
[]
whats the best way to store guild settings in db
like this ['id_user', 'id_user']?
I keep getting an error with vsc that says this ```py
line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Message' object has no attribute 'channle'
read
you spell channel wrong
π₯£
channel, not channle
Ok thank you it works now π
Ye
Make list like
@client.event
async def on_message(message):
owner = ["id of owner"]
if message.author.id in owner:
return
does it really? i thought roles would be perfectly synced like channels and other attributes under the guilds intent
well, unless the cache resets itself, in which case your task loop randomly fails and you only get to know about it when you realize your server status stopped updating...
Hello guys, my bot keeps speeding/slowing down randomly while playing music and i dont know why or what is causing this problem, in the screenshots you can see that i am using ffmpeg with a link and these ffmpeg options. Does anyone know why this problem is occuring?
import discord
import asyncio
from discord import Intents
from discord.ext import commands
intents = discord.Intents.default()
intents.typing = True
intents.presences = True
intents.members = True
client = discord.Bot(intents=intents)
@client.event
async def is_owner(message):
owners = ["id_user", "id_user"]
if message.author.id == owners:
return
else:
await message.channel.send("You don't have permission to use this command")
@client.event
@commands.check(is_owner)
async def on_message(message):
if message.content == "test":
await message.channel.send("Hello world!")
client.run("TOKEN")
Yes, I did that too but it still doesn't work. They tried to use the command and got a message that they don't have permission.