#discord-bots
1 messages · Page 134 of 1
Sure
WALLPAPERS_ID = 123
WALLPAPER_REQUESTS_ID = 456
@bot.listen()
async def on_message(message: discord.Message) -> None:
if message.channel.id == WALLPAPERS_ID:
# add star emoji
elif message.channel.id == WALLPAPER_REQUESTS_ID
# add check and cross emoji
!d discord.Message.add_reaction
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this. If nobody else has reacted to the message using this emoji, [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") is required.
Changed in version 2.0: `emoji` parameter is now positional-only.
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`.
see here for how to add a reaction
is that the whole code i need for the bot? where do i put the token? sorry i'm new to this lol
Do you have a basic bot structure set up already?
is the WALLPAPERS_ID and REQEUSTS_ID the ID of the channel?
yes
i don't have any structure
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html I would recommend reading this to get a basic bot up and running
It's a pretty simple getting started guide
actually yes
i have this:
import discord
from discord.ext import commands, tasks
import os
import asyncio
import random
from itertools import cycle
# Your bot's prefix.
client = commands.Bot(command_prefix='!')
# Creates an arraylist containing phrases you'd like the bot to cycle through.
status = cycle(['DM me!', 'Wanna talk?', 'Lets chat', 'Why wont you DM me?', 'Cmon, talk to me...'])
# Do not add apostrophe's to the arraylist.
@client.command()
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)
@client.event
async def on_ready():
print("Bot was deployed sucessfully !")
while True:
await client.change_presence(game=Game(name='DM me!'))
await asyncio.sleep(3)
await client.change_presence(game=Game(name='Wanna talk?'))
await asyncio.sleep(3)
await client.change_presence(game=Game(name='Lets chat', type = 3))
await asyncio.sleep(3)
await client.change_presence(game=Game(name='Why wont you DM me?', type = 2))
await asyncio.sleep(3)
@client.event
async def on_message(message):
message.content = message.content.lower()
author = '{0.author.mention}'.format(message)
# Stops the bot from talking to itself.
if message.author == client.user:
return
# Add/edit your responses here.
if message.content.startswith('hello'):
msg = 'Hello, how are you? {0.author.mention}'.format(message)
await message.author.send(msg)
if message.content.startswith('hey'):
msg = ''
randomlist = ['Hello! {0.author.mention}'.format(message),'Oh, hey!','Hello {0.author.mention}'.format(message),'How are you doing?','Heyy..','Hey, is there anything you would like to talk about? {0.author.mention}'.format(message),'Hiya!']
await message.author.send(msg + (random.choice(randomlist)))
@client.event
async def on_ready():
print('Bot running as...')
print(client.user.name)
print(client.user.id)
print('------')
change_status.start()
@tasks.loop(seconds=10)
async def change_status():
await client.change_presence(activity=discord.Game(next(status)))
client.run(" Paste your token between these speech marks.")
How does editing embeds work? I first send a message to a channel that contains an embed, which has a title and a description. If the user reacts to the message with the embed, the embed should edit to include the previous content plus some new stuff. And if they edit it again, it should contain both the previous ones plus something new, and the cycle continues.
Sending the message works fine, and so does the first reaction. However, every reaction after that discards the previous one. I'm bad at explaining things, so here's an example. If I first sent "foo", and they reacted, it should send "foo bar". Then if they react again, it should edit to be "foo bar baz". Right now I'm getting "foo" then "foo bar" but then "foo baz".
Any clue what the issue could be?
Looks like you already have an on message event
Just work the new code into there
Should be just a if/elif statement
do i need to modify anything to make it work or just throw it in?
Just throw it in
Other than that the code is a bit rough around the edges
it sounds like you got the embed editing just fine, but your code isnt correctly generating the new text like you want it to
what do you mean by that sorry?
The code is a bit... outdated or follows practices not recommended
also your
# add star emoji
is that just
await add_reaction(emoji id, /)
Not directly the cause of any issue of course
It generates the new embed with message.embeds[0].title + new_stuff
what is the purpose of that slash
where emoji is an emoji yeah, so for instance:
@bot.event
async def on_message(message):
await message.add_reaction('⭐')
It's from the documentation, which means that the emoji is positional only
oh okay cool
My issue is message.embeds[0].title is always the initial value, it never updates
class config(Select):
async def callback(self, interaction):
if self.values[0] == 'Configs':
with open('guilds.txt', 'r') as file:
guildid = file.read()
guildid = guildid.split()
if str(interaction.guild.id) not in guildid:
with open("configs.json", "r") as f:
guilds = json.load(f)
await update_guild(guilds, interaction.guild)
>
Traceback (most recent call last):
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/ui/view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "main.py", line 525, in callback
await update_guild(guilds, interaction.guild)
UnboundLocalError: local variable 'guilds' referenced before assignment
thanks for your help @sick birch
no worries
can you send a paste of your code? it would seem that somehow your message isnt actually being updated
Idk why that's the case, since I do message.edit(embed=new_embed) each time. Shouldn't editing the message's embed change the value of message.embeds?
embed.title += stuff
One sec
for some reason my code is giving me this error and I have no idea how to fix it
its under that
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Is await update_guild(guilds, interaction.guild) supposed to be inside your 2nd if statement
yes
if you select the config option
then if your not found in it
Well you haven't indented it properly in that case
it seems I havent
oh, sure enough it doesnt seem to get updated
i can never catch those
Is there another way to access the embed title that you know of?
>
Traceback (most recent call last):
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/ui/view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "main.py", line 526, in callback
with open(interaction.guild.id, "w") as f:
TypeError: expected str, bytes or os.PathLike object, not int
interaction.guild.id```
how can I make a file with the guilds id
with open(str(...), 'w') as ...
ill try it
prob add an extension tho, like .txt or whatever the file will hold
my assumption was that the message sent by the bot would be stored in the message cache, which message_update events will later access and update the message in-place, but after going through abc/message/state.py, it appears that the message object returned by ctx.send() isnt the same object as the one cached by the connection state
however, message.edit() still constructs a new message object based on the data received after making the API request, so using message = await message.edit(...) should work as expected
str(interaction.guild.id).json what about a json file @oblique laurel
Hmm, I need to create the new embed before I edit the message though
i dont need str right
so i have some stuff in a discord view class
how do i make the view do some stuff to the message upon startup
Prob use an f string there, like f'{...}.json'
thats fine as you already have the message object at the start, the assignment is simply to replace it with the updated message
although i would also consider storing just the text embed rather than relying on the message embed getting it from the message each time
alr alr
Eyyy doing message = await ... worked. Feels a bit like magic, but thanks a lot lol
@mt.tree.command(name='configs', description='Check your configs!')
@app_commands.describe(choice='Choose an option!')
@app_commands.describe(word='Choose a word!')
@app_commands.choices(choice=[
discord.app_commands.Choice(name='Check', value=1),
discord.app_commands.Choice(name='Add', value=2),
discord.app_commands.Choice(name='Remove', value=3)
])
async def configs(interaction: discord.Interaction, choice: discord.app_commands.Choice[int], word=''):
if choice.value == 1:
Traceback (most recent call last):
File "main.py", line 518, in <module>
async def configs(interaction: discord.Interaction, choice: discord.app_commands.Choice[int], word=''):
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 889, in decorator
command = Command(
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 685, in __init__
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 390, in _extract_parameters_from_callback
raise TypeError(f'parameter {parameter.name!r} is missing a type annotation in callback {func.__qualname__!r}')
TypeError: parameter 'word' is missing a type annotation in callback 'configs'
```\
wait
nvm got it lol
given that it is a weird (and undocumented) quirk of dpy, you might want to add a comment explaining it, or go with my suggested alternative of keeping the Embed in a variable and updating that embed inplace - i would figure the mutability of embeds is more intuitive than knowing exactly how d.py handles their inplace object updates
Couldn't that eat up some ram tho, if there was enough of this happening at once?
an embed object is like, 200 bytes in size
of course that could be bigger, perhaps at most 6kb, but you're not leaking memory or anything
Hey, using the webhook system, how do you ping roles?
if choice.value == 1:
with open('guilds.txt', 'r') as file:
guildid = file.read()
guildid = guildid.split()
if str(interaction.guild.id) not in guildid:
with open(f"{interaction.guild.id}.json", "w") as f:
f.write("{}")
with open(f"{interaction.guild.id}.json", "r") as f:
guilds = json.load(f)
await update_guild(guilds, interaction.guild)
with open(f"{interaction.guild.id}.json", "w") as f:
json.dump(guilds, f, indent=4)
with open("guilds.txt", "a") as f:
f.write(f"{interaction.guild.id}\n")
await interaction.response.send_message("Configs set up.", ephemeral=True)
if str(interaction.guild.id) in guildid:
with open(f"{interaction.guild.id}.json", "r") as f:
guilds = json.load(f)
words = guilds[f'{interaction.guild.id}']['words']
await interaction.response.send_message(f"Words: {words}", ephemeral=True)
<@&roleid>
Traceback (most recent call last):
File "/home/runner/miner-bot/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 526, in configs
await update_guild(guilds, interaction.guild)
File "main.py", line 26, in update_guild
guilds[f'{guild.id}']['words'] = ''
KeyError: '1040483695976517732'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/miner-bot/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/miner-bot/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/miner-bot/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 'configs' raised an exception: KeyError: '1040483695976517732'
omg. i thought it was just <@id>
I’m trying to just have it like cleaned up I want all the messages in the channel ids section to be sent to my channel I’d
If you're using a json file or a dictionary, make sure all keys are strings
wym
At the end you have a key error
yea its not updating the info
A bunch of numbers, which tells me you're not parsing an int as a string
with open(f"{interaction.guild.id}.json", "r") as f:
guilds = json.load(f)
await update_guild(guilds, interaction.guild)
with open(f"{interaction.guild.id}.json", "w") as f:
json.dump(guilds, f, indent=4)
Just do str_guild_id = str(guild_id)
and use the str version to guild id as your dictionary/json item
what
guild_id is guild.id
i dont know your code. I just know keys need to be strings
path = f"{interaction.guild.id}".json
thne
with open(path, "r")
that just raises errors
@drifting arrow
Sorry was busy.
If your file name is a guild_id then it should work.
1235.json is fine
but the issue comes down to your keys. Keys are the 'named' values in your dictionary..
mydictionary = { 'key1': "Hello World", 'key2': "APPLES!"}
@drifting arrow i got it working
but i have another issue
if choice.value == 2:
with open(f"{interaction.guild.id}.json", "r") as f:
guilds = json.load(f)
format = f"'{word}', "
guilds[f'{interaction.guild.id}']['words'] -= format
with open(f"{interaction.guild.id}.json", "w") as f:
json.dump(guilds, f)
await interaction.response.send_message(f"Removed the word {word}.", ephemeral=True)
e Ignoring exception in command 'configs'
Traceback (most recent call last):
File "/home/runner/miner-bot/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 544, in configs
guilds[f'{interaction.guild.id}']['words'] - format
TypeError: unsupported operand type(s) for -: 'str' and 'str'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/miner-bot/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/miner-bot/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/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 876, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'configs' raised an exception: TypeError:
pretty sure you cant minus a string from a string.
in your json file, store the words as a list.
and then simply remove that word from the list as needed
a json file is just a dictionary.
mydictionary = {'mykey': ['list_item_1', 'list_item_2']}
wait how would I do that?
by learning basic python
first of all u are storing more words in a string when a better approach would be to use a list
Traceback (most recent call last):
File "/home/runner/G9/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/G9/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1015, in invoke
await self.prepare(ctx)
File "/home/runner/G9/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 932, in prepare
await self._parse_arguments(ctx)
File "/home/runner/G9/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/G9/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 691, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: question is a required argument that is missing.```
@client.command(name='8ball', description='Let the 8 Ball Predict!\n')
async def _8ball(self, ctx, question):
responses = ['As I see it, yes.',
'Yes.',
'Positive',
'From my point of view, yes',
'Convinced.',
'Most Likley.',
'Chances High',
'No.',
'Negative.',
'Not Convinced.',
'Perhaps.',
'Not Sure',
'Mayby',
'I cannot predict now.',
'Im to lazy to predict.',
'I am tired. *proceeds with sleeping*']
response = random.choice(responses)
embed=discord.Embed(title="The Magic 8 Ball has Spoken!")
embed.add_field(name='Question: ', value=f'{question}', inline=True)
embed.add_field(name='Answer: ', value=f'{response}', inline=False)
await ctx.send(embed=embed)```
How are you invoking the command
wdym
Are you typing just the _8ball command with nothing after it
im typing >_8ball question
Whydo you have self?
oh shit
Consider using *, question
it consumes the rest of the message instead of only 1 wors
wors
Word
erm :D
check dms lol i sent it yesterday
oo saw it
i didnt get the notification 💀💀💀💀
What embed colour is this
?tag invis embed
This is not a Modmail thread.
!tag ?
k
Nah dpy tags
When the hex
"What color is your embed?"
- Andrew Tate, Verified Discord Bot Developer
lmaooo
what
Guys always remember to use the correct naming convention for your variables. Especially if they're database tables and records 
screaming snake for functions
People remove vowels from words and think it's an excellent naming convention
my naming convention ```py
class ApplicationCommandInteractionDataResolved:
couldnt think of shorter ones
have fun
My eyes hurt
then rename it and makes the whole thing unusable?
I can't, they're from the work enviroment and they're already in production
so its a lifetime fuckery now
also i can't show you the whole database but it's like very damn huge
and all namings for both records and tables are like that
so yeah i'm pretty screwed up
Is it possible to update voice channel name every seconds?
@tree.command(description="VC Timer")
async def timer(interaction, time: int):
channel = client.get_channel(1042018244548108349)
try:
seconds = int(time)
except ValueError:
await interaction.response.send_message("Please enter a valid number.")
return
await interaction.response.send_message(f"Timer started for {seconds} seconds.")
new_name = f"Timer: {seconds}"
await channel.edit(name=new_name)
lol why you would even need that
i need a timer
good i can't even remember module names
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
thanks
Thank you!
shh rate limit helps people learn
its even every seconds..
you'll get ratelimited
oh...
cri about it
Discord's gonna suck your soul out
rude
.
how about every 3 or 5 seconds? it will limited?
It will suck even more
just use a text with a unix timestamp?
But where are ashley and hunter? i've not saw them in a while
it will pretty much work as a timer
It won't suck only with 5 min interval at least
umm...
Hunter might be busy with studies, its his School's final year (class12th)
ashley had been gone for a month
oh very nice for him
me who dropped after school
Bruh in Italy we don't even have "grades"
dropped?
same here
We finish with the fifth year of high school
im secondary 4
Here it's just 1-4 is elementary 5-8 is secondary and 9-11 is high
School naming convention be like
6 years of primary and another 5 more for secondary
we have 5 years of elementary, 3 of secondary and then you will have to choose a specialized high school, normally you would do 5 years in high school, but with some of them you can have a degree after 3 years once you're 16, but some of them like technical institute (which i did) requires 5 years for the degree
Is there discord bots school
nope lmao
us
We're gonna go extinct
chill 💀💀💀
If noone teaches young discord bot developers they won't grow up 😢
what are we doing here then we teach nextcord pycord dpy u name it we have taught it
missed disnake and hikari
Ubuntu 22.10 seriously affected my grammar and braincells
We are so nice people
😡
🦶🦶

ikr no discrimination
how to get your bot commands to only work for admin roles
???
sry typo
@discord.ext.commands.has_permissions(**perms)```
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 has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
wat docs like discord.py ones?
whatever library's documentation you want
you need to know object names and their path
Braincell* 
Oh btw to send embeds I have to use
await ctx.send(embeds=(list[“embed1”, “embed2” . . .]))
```?
.. Are you familiar with python?
interaction.channel.send
You still have to respond though, possibly with defer
wait wut, my bot's token magically stopped working after i did nothing
me can't run token
That is not what I said.
i did
ok..?
it sent a very long error message
can i dm it
cus def not sending it here
smth about access denied
Why not
it is
Are you on replit?
yes, does that happen a lot
Then it's a replit moment
rip
ill run it in vscode
alr
i still have an error but it doesn't have to do with the token
idk what htis stuff mens
This is the part of traceback right?
If so, send the full traceback please
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Just telling, the most important part of traceback in python is usually in the bottom
i will send ze message but i gotta remove the personal stuff from da terminal first
me confused
Windows or Mac?
macos
Getting
[SSL: CERTIFICATE_VERIFY_FAILED]on Python 3 on OS X?
Navigate to yourApplications/Python 3.X/folder and double click theInstall Certificates.commandto fix this.
Happy coding!
wut
ok
bro wut
wait, can somebody explain the replit one 2
it is partially replit but also there's parts about the actual code
What's with it
smth about access denied
when i run the bot
it started today and i hadn't changed anything since i worked on it yesterday
One sec
hopefully me didn't miss smth that someone could hack me with
Check this out
lol
ye ik
buy a raspberry pi
why
That basically means you get ratelimited
or use one of the thousand cheap hosting services
does replit hosting cost mny
Raspberry is hard to buy rn isn't it
bruh dont be such a dick
ok
what does ze error message mean tho
Put the html code into browser and you'll see
Or read html if you can
I was thinking about buying it like several months ago and back then pi 4 with 4gb costed like 300$+ and was sold out
But yk I live in Russia here we have weird stuff with electronics happening sometimes
Replit still uses shared IP
how duz that affect me
Discord bot is a web app
Many people make requests from same IP = more than 50 requests per second or other per-route thresholds violations = ratelimit
rip
but i won't get the error if i write it locally right?
after i fix the cert thing
If you run it locally
I bought mine for 100 lol
Doesn't matter where you write it
^
idk if me gonna run it 24/7 because i am poor i just want it to work for fun
eventually i will tho
Eventually I just remembered I have some computer scrap and I built a server with something like intel pentium and 3gb of ddr3 ram
dope
Was doing pretty well until I updated to ubuntu 22.10 had to downgrade entire thing to 22.04.1
rip
@mt.event
async def on_message(message):
user = message.author
guild = message.guild
if not guild:
await user.send("Get out of my DMS.")
Traceback (most recent call last):
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "main.py", line 570, in on_message
await user.send("Get out of my DMS.")
AttributeError: 'ClientUser' object has no attribute 'send'
the author was the own bot, your logic implies recursion
you're asking the bot to get out of its own dms, gg
Remember on_message is triggered by messages your bot sends as well
So you might want to slap an if-statement up there to make sure you ignore its own messages ```py
if user == client.user:
return
Addition to Jack is to also add if a message can even get send. Some users have their DM closed this will then raise an HTTPException, I also recommend making this check if the user is a bot since those won't care anyways.
was cog loading changed somehow
for filename in os.listdir("./cogs"):
if filename.endswith('.py'):
try:
bot.load_extension(f'cogs.{filename[:-3]}')
print(f"{filename} loaded")
except Exception as e:
print(f"Exception in {filename}\n\n {e}")
else:
if filename != "__pycache__":
print(f'{filename[:-3]} Not an .py file')
RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited bot.load_extension(f'cogs.{filename[:-3]}')
prob should google before askin
im trying to make a dropdown selection but it gives me this error:
Ignoring exception in command menu:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 167, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\ADMIN\Desktop\r.lykn\code.py", line 18, in menu
await ctx.send("Menus!",view=Select())
File "C:\Python310\lib\site-packages\discord\abc.py", line 1368, in send
raise InvalidArgument(f'view parameter must be View not {view.__class__!r}')
discord.errors.InvalidArgument: view parameter must be View not <class '__main__.Select'>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InvalidArgument: view parameter must be View not <class '__main__.Select'>
my code is this:
class Select(discord.ui.Select):
def __init__(self):
options=[
discord.SelectOption(label="a",description="h"),
discord.SelectOption(label="b",description="hh"),
discord.SelectOption(label="c",description="hhh")
]
super().__init__(placeholder="Select an option",max_values=1,min_values=1,options=options)
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message(content="h", ephemeral=False)
class SelectView(discord.ui.View):
def __init__(self):
super().__init__()
self.add_item(Select())
@bot.command()
async def menu(ctx):
await ctx.reply("menu",view=Select())
im using this btw https://gist.github.com/lykn/a2b68cb790d6dad8ecff75b2aa450f23
A gist explaining the right way to make drop down menus/select menus/selects in discord.py v2(version 2.0.0a) - selects_or_dropdowns.md
nevermind i got it working
view accepts a View object not a Select object, you will have to add the select menu to a view first and then send that view
view = discord.ui.View()
view.add_item(Select())
await ctx.send(..., view = view)
yeah thats what i got wrong
nice
bot.load_extension is now an async method, you can simply await the method and it'll work
very
how to return a message where only the person using the command can see it with the slash command?
What is return a message
by using the ephemeral keyword argument
how do i give user a role
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
await interaction.user.add_roles("role name" . .. .)?
Why won’t my? bot rename the ticket
@slate swan u need to show the code
@slate swan
u cant rename the channel by sending a message...
await interaction.channel.edit(name='name')
that should work
I’m using ticket tool
Shouldn’t I be able to?
no
The bot is probably ignore other bots' messages
^^^
@slate swan you can't rename via another bot, make your bot change channel name
yea^
Maybe interaction.channel.edit(name=limited-9834")
.
Ooooo ty guys fr had me confused 😭
yea yw
i'm not sure i should ask here but i pip installed dhooks but for some reason can't import it
Yikes the last update of that pip was 2 years ago, you sure want to use this?
zamn i was following a tutorial from 2020 without noticing
what module should i use to easily send data to webhooks
No clue never worked with webhooks.
discord.webhook
!d discord.TextChannel.fetch_webhook
No documentation found for the requested symbol.
!d discord.ext.commands.Bot.fetch_webhook *
await fetch_webhook(webhook_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook "discord.Webhook") with the specified ID.
Changed in version 2.0: `webhook_id` parameter is now positional-only.
!d discord.Webhook.send
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using the webhook.
The content must be a type that can convert to a string through `str(content)`.
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.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects to send.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
Easy peasy
thankss
lemon squeezy?
Indeed
how can I get all the invite codes a user has made?
invites = list(filter(lambda inv: inv.inviter.id == user.id, ctx.guild.invites))
k bc i didnt understand the docs
Traceback (most recent call last):
File "/home/runner/miner-bot/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/miner-bot/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/miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 876, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'invites' raised an exception: TypeError: 'method' object is not iterable
invites = list(filter(lambda inv: inv.inviter.id == user.id, (await ctx.guild.invites())))
[<Invite code='TBCfJQqzVr' guild=<Guild id=1040483695976517732 name='bot testing' shard_id=0 chunked=True member_count=5> online=None members=None>, <Invite code='jjkJPVuv' guild=<Guild id=1040483695976517732 name='bot testing' shard_id=0 chunked=True member_count=5> online=None members=None>]
any way to make this nicer?
This is nicer repr is gut :3
No clue half the code is scrambled.
Indention most likely
Well I have no idea if that is the case since I can't see anything.
But seeing as this top code is indented that far out there is likely something wrong.
When you create a class the first indent is usually the class so it appears to be there.
2 indentions in and your inside the first indention of a function.
Why are you also adding app commands to a Cog but they use groups..? And a tree..? 
Help

!remind 5d don't touch pycord
Sorry, you can't do that here!
Still same applies it's on the first indention and you have no self inside a class instance, only inside the methods.
See "self" or "this" as a private protected variable.
And not mutable inside a class.
any ideas for what can i do w my bot?
Well.. at the root lol
Make some friends :3
lol why not have it ping a random online user to chat.
tldr you can't use self inside a class like that.
Do it in the init
It's a bit ambiguous, what do you mean by "where would i add it ?"?
Both would work.
if i want it to message reply though, id use ctx.reply, right?
Yes.
got ittt tyy
how would i make a command to send messages from the console? or would i be better off using the echo command
guys where do you host a bot for free?
Afaik everyone that I know of that is actively helping here all have either self hosting, paid hosting or just code for fun.
Generally involving the console is pretty messy since you'd need to open a second console app and the input it there to make it async etc... so yeah, I recommend to just use echo.
thx
Affordable hosting providers:
• OVH Starting at $3.35/mo for 1 core, 2GB RAM, 20GB SSD
• DigitalOcean Starting at $5/mo for 1 core, 1GB RAM, 25GB SSD
• Linode Starting at $5/mo for 1 core, 1GB RAM, 25GB SSD
• Vultr Starting at $2.50/mo for 1 core, 512MB RAM, 10GB SSD
• AWS Lightsail Starting at $3.50/mo (first month free) for 1 core, 512MB RAM, 20GB SSD
• Time4VPS Starting at €3.99/month for 1 core, 2GB RAM, 20GB SSD
• VIRMACH Full Windows and Linux Desktop VPS starting at $7/mo and $1/mo respectively
• Netcup Starting at €2.62/mo for 1 core, 2GB RAM, 20GB SSD
• GitHub education Free credit and other offers for students
• Microsoft students Free credit for students
• Google Cloud free tier
My random bot I started recently handles welcome images pasting member pfp onto a background and also runs giveaways. Future implements I plan to include are a 2 hour timer to let people know when the server may be bumped again and a staff member application modal that sends an embed to the staff channel with the answers they input
TYSM those are great ideas i will try
how would i make an echo command
hold on im gonna try and make one and tell me what i did wrong
async def load():
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await mt.load_extension(f'cogs.{filename[: -3]}')
async def main():
await load()
Traceback (most recent call last):
File "main.py", line 582, in <module>
asyncio.run(main())
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "main.py", line 24, in main
await load()
File "main.py", line 21, in load
await mt.load_extension(f'cogs.{filename[: -3]}')
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1012, in load_extension
await self._load_from_module_spec(spec, name)
File "/home/runner/miner-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 943, in _load_from_module_spec
raise errors.NoEntryPointError(key)
discord.ext.commands.errors.NoEntryPointError: Extension 'cogs.ping' has no 'setup' function.
is there any event name about detecting someone boosting a server?
async def on_message():
if message.type == discord.MessageType.premium_guild_subscription:
why wont my cog load
thanks 🤝
yw
Hello, I'm using discord.py and I'm wondering how to make a field in embed to be on 1 line. For example, I have a field with name 'test' and value 'check'. I can do something like this: test check
But how can I do something like this: test check inline=True doesn't work
You can't use fields then
Add it to your description
Okay, but is there a way to change size of the text in the description?
No
And the last question, is there some other, more customizable alternatives to embeds?
No
Discord is a text messaging platform not a front end UI framework
Got it, thank you!
^
ˢᵐᵒˡˡ ᵗᵉˣᵗ
@commands.Cog.listener("on_command_error")
async def on_sync_error(self, interaction: discord.Interaction, error: app_commands.AppCommandError):
if isinstance(error, app_commands.CommandOnCooldown):
await interaction.response.send_message(str(error), ephemeral=True)
how can I add a cooldown to command
in cogs
!d discord.app_commands.checks.cooldown
@discord.app_commands.checks.cooldown(rate, per, *, key=...)```
A decorator that adds a cooldown to a command.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.
The `key` function can optionally be a coroutine.
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandOnCooldown "discord.app_commands.CommandOnCooldown") is raised to the error handlers.
Examples
Setting a one per 5 seconds per member cooldown on a command:
I remeber doing smth like that a while back its still just ascii art
d = '0'
print(sid) a = 0 b = 0 c = 0 d
File "main.py", line 37
d = '0'
^
IndentationError: unindent does not match any outer indentation level
? read the error ?
i did
your_twilio_phone_number = raw_config['Twilio Phone Number']
ngrok = raw_config['ngrok_url']
client = Client(account_sid, auth_token)
server_id = int(raw_config['server_id'])
app = Flask(__name__)
@slash.slash( name='call', description='F', guild_ids=[server_id], options=[ discord_slash.utils.manage_commands.create_option( name='phone', description='With +1', required=True, option_type=3 ), discord_slash.utils.manage_commands.create_option( name='digits', description='Seg', required=True, option_type=3 ), discord_slash.utils.manage_commands.create_option( name='name', description='Seg', required=True, option_type=3 ), discord_slash.utils.manage_commands.create_option( name='companyname', description='Seg', required=True, option_type=3 ) ])
async def _call(ctx=SlashContext, phone=str, digits=str, name=str, companyname=str):
await ctx.send('Nothing Just Want To Avoid Error')
open('Extra/Digits.txt', 'w').write(f'{digits}')
open('Extra/Name.txt', 'w').write(f'{name}')
open('Extra/Company Name.txt', 'w').write(f'{companyname}')
call = client.calls.create( url=f'{ngrok}/voice', to=f'{phone}', from_=f'{your_twilio_phone_number}' )
sid = call.sid
print(sid)
a = 0
b = 0
c = 0
d = 0
What is that abomination
im pretty sure thats not the code that is being run
otherwise it might have a problem with whitespaces in ur code
why r u using d.py slash anyways?
import discord
import config
import requests
import os
import asyncio
import datetime
import time
import random
from discord import Intents
from discord.ext import commands
from discord import app_commands
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents = discord.Intents.all())
bot.remove_command('help')```
code:
```py
@bot.command()
@commands.has_permissions(administrator=True)
async def start(ctx, mins : int, *, prize: str):
embed = discord.Embed(title='Giveaway!', description= f"{prize}", color = 0x2E79FF)
end = datetime.datetime.utcnow() + datetime.timedelta(seconds = mins*60)
embed.add_field(name='Current time: ', value = f"{end} UTC", inline=False)
embed.set_footer(text = f'Ends {mins} minutes from now!')
my_msg = await ctx.send(embed = embed)
await my_msg.add_reaction("📀")
await asyncio.sleep(mins*60)
new_msg = await ctx.channel.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(bot.user))
winner = random.choice(users)
await ctx.send(f"Congratulations {winner.mention} won {prize}! ")
await winner.send('Hiya')
its start the giveaway
but not finish it
error code
Traceback (most recent call last):
File "C:\Users\אמיר\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\אמיר\Desktop\servers\Discord Ne0r4i Stock\Official Bot\official_bot_start.py", line 100, in start
bot.run(config.TOKEN)
AttributeError: 'async_generator' object has no attribute 'flatten'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\אמיר\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\אמיר\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\אמיר\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'async_generator' object has no attribute 'flatten'```
someone?
async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") representing the users that have reacted to the message.
The `after` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
Changed in version 2.0: `limit` and `after` parameters are now keyword-only.
Examples
Usage...
async def on_message(message):
if message.author != client.user:
channellist = [1034897577478455337, 1025864145150685194, 1038870393815044257, 1033090064827306086]
if message.channel.id in channellist:
channel = client.get_channel(1041876398849146910)
await channel.send(f"@everyone {message.content}") ```
Does anyone know how I can have my `ids` in the `channellist` section messages to be sent to `1041876398849146910`
wdym?
oh i get it
!d discord.Embed
fetch the user and then user.send
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
Can't you just put channellist in your message send
Oh you mean user IDs from the messages in those channels
does someone know how to help me
What is the problem
yea send the traceback
ok so i run the kick command with an account that doesnt has the perms and it doesnt show the embed
i mean you need the kick_members perm and the account doesnt has it and no it doesnt kick it
wait let me check
show the command
I want the bot to get all messages from channellist and send them to channel = client.get_channel(1041876398849146910)
show code
Call the discord.Color.red
@client.command()
@has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f"{member} has been kicked | Reason: {reason}")
@kick.error
async def kick_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
embed = discord.Embed(title="You don't have the permissions to do so.", color=discord.Color.red)
await ctx.send(embed=embed)
okok let me retry
it works now, i thank you very much :)
Is that not what it does as written?
send the tracbeack
*traceback
the code seems fine on a first glance
\u001b[bold;30m
afafa
\u001b[0;40m\u001b[1;32mThat's some cool formatted text right?
\u001b[1;40;32mThat's some cool formatted text right?
?
Hey I have a question, I have a Discord bot that runs 24/7. I pass a Discord ID from PHP to a python script, how can I now call a function from a python script to a Discord bot (other python script) and give a return to the other script that it worked?
websockets
what is the default value for file parameter in discord.Webhook.send ? if I put None it will throw an error
prob a MISSING
Why won’t it send a embed when I do roll then a number
answer for me?
ofc
If i have a look on the picture. Which port have a discord bot lol
roll(int) lmao first of all u are calling roll as in recursion and then passing a data type 💀
only thing i can say is learn python
lmao just coz the sample code dosent use discord.py dosent mean it cant be used it can very well be integrated with discord bots
🧐
traceback:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: View.to_components() missing 1 required positional argument: 'self'
my code:
class Texting(discord.ui.TextInput):
def __init__(self):
super().__init__(placeholder="hello", type=4)
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message("thanks for sharing!!!!!!")
class TextingView(discord.ui.View):
def __init__(self):
super().__init__()
self.add_item(discord.ui.TextInput(label="hhhhh", placeholder="hhhhhhhhhhhh"))
@bot.command()
async def texting(ctx):
await ctx.reply("abc",view=TextingView)
???
ur replying to wrong message that was for //error
Oh okay 🙂
you named it leo
leo.run
enter some code under on_member_join
also btw you spelled member wrong
oh
can anyone help?
TextInput can only be used with modals
And you have to create an instance of your view by calling it
@commands.Cog.listener("on_command_error")
async def on_sync_error(self, interaction: discord.Interaction, error: app_commands.AppCommandError):
if isinstance(error, app_commands.CommandOnCooldown):
await interaction.response.send_message(str(error), ephemeral=True
how can I add cooldown to cogs?
@shrewd apex i dont get it, i tryed it so:
Script after php args got:
import asyncio
import websockets
uri = 'ws://0.0.0.0:8000'
async def send_message():
async with websockets.connect(uri) as websocket:
message = input("msg: ")
await websocket.send(message)
print(f"[ws client] message > {message}")
#answer = await websocket.recv()
#print(f"[ws client] answer < {answer}")
asyncio.get_event_loop().run_until_complete(send_message())
Script (Discord Bot) i added following:
async def response(websocket, path):
message = await websocket.recv()
channel = client.get_channel(MY_CHANNEL_ID) # access to channel
await channel.send(f'websockets: {message}')
server = websockets.serve(response, '0.0.0.0', '8000')
asyncio.get_event_loop().run_until_complete(server)
But there is even no message coming to my channel
Dude there is no trackback I'm still coding the event I don't know how to code what I want it to do
#bot-commands
first of all the ports either need to be forwarded or both need to be in local network
second u cant start websocket and bot at same time that way u need a async context manager
third i am sleepy so gn someone else will help u bai bai
both is scripts running on one server
And about the second - Can anyone else help me?
async def on_message(message):
if message.author != client.user:
channellist = [1034897577478455337, 1025864145150685194, 1038870393815044257, 1033090064827306086]
if message.channel.id in channellist:
channel = client.get_channel(1041876398849146910)
await channel.send(f"@everyone {message.content}") ```
Does anyone know how I can have my `ids` in the `channellist` section messages to be sent to `1041876398849146910`
isnt that what ur doing?
oh do I already have it done I thought I needed more
u didnt test it?
how do i make a modal?
someone help
if i wanna put just one user do i need to do discord.Member = {their-id} ?
What happens if the user runs the credits command without mentioning a user?
i'd just like to make like an embed where i can put my bot
so even if they do .credits @slate swan the bot is still gonna come out
oh no... i pinged someone
What does the bot do with the user?
.credits and then just show the bot's profile picture, and the name
How would I make it so I can customize my bot through a website?
be more specific
of the bot, and not of anyone else
thats a really complex question
Is it possible with discord.py?
What kind of modal? https://github.com/Rapptz/discord.py/blob/master/examples/modals/basic.py
class TextModal(discord.ui.Modal):
def __init__(self):
super().__init__()
i know that that makes the actual modal, but how do i make a discord.ui.View
idk text?
text?
what types are there
short and long
oh short
a lot of aliases
i just want to know how to set it up
🔺 that's the example
label="label"
style=discord.TextStyle.short
placeholder="idk something"
min_length=4
max_length=50
etc..
oh
How to give a Discord bot an arg from other script. With normal script it works with: sys.argv
Is there a way to implement in discord bot
just import the bot
or have a run func
so import bot and then create async function which runs a channel.send?
and just run the function basically without any event or loop?
ig idk what ur trying to do tbh so I cant tell ya
I try this, you understand me?
There i have said i have an argument in script1, but if you have an answer how to get the sys.argv directly to the discord bot script pls tell me
im confused
i cant help you out here
So you dont know what i mean or how to do it?
I can help you to understand my question ^^
@alpine cove
why not just use a database
also not even sure u can run a script from inside a discord bot lol
or how that would even work
both
Okay well, thats really simple xD
Thanks for the idea xD
maybe someone else will be able to help you
just will do it with database, even if this is not the best way I think
Bro could you pls just say me why it does not work:
async def password_reset_code():
while True:
channel = client.get_channel(815263639333371908)
message = "test"
await channel.send(f"{message}")
await asyncio.sleep(10)```
and Thank you
dont use pycord
dont use "client" use "bot" instead
second of all: use tasks
print channel
But i set it up with: client = commands.Bot(command_prefix="!")?!
yea use bot
But it is underlindes
async def on_message(message):
if message.author != client.user:
channellist = [1034897577478455337, 1025864145150685194, 1038870393815044257, 1033090064827306086, 1039968764927692863]
if message.channel.id in channellist:
channel = client.get_channel(1041876398849146910)
await channel.send(f"@everyone {message.content}")```
**Why doesn't the bot send messages to my id?**
ur code seems fine
no traceback?
none
yea do bot = then
And i have to run the function with: password_reset_code()?!
in most text editors you can do ctrl+r to replace all strings
no bot bot to message
But it is the same just other name?!
yea
I didnt say it would fix the error
do this:
with which function does it work?
Is your messages intent enabled
smart dude
it workes just doesn't get messages from other servers for some reasons
*might have
servers the bot is part of?
I have emanle all intends
client = commands.Bot(command_prefix="!", intents=discord.Intents.all(), help_command=PrettyHelp(color=discord.Color.dark_gold(), active=10))
And on Discord settings also
I want the bot to get messages from other server the bot isn't in
what is PrettyHelp? is that a discord inbuilt or a custom?
Do I really have to tell anything
nope
?
but why does this not work?
a bot is basically just a user
yeah ik
You can't keep saying 'not work'
I don't think message is even defined here
Yeah but the bot should only send in a channel he have access to
I wasnt even responding to you
i set a value for message before?
bruh xD
I have an autocomplete descriptor
async def my_autocomplete(self, interaction: discord.Interaction, current: str) -> list[app_commands.Choice[str]]:
options = await database.fetch(...)
obviously this is not feasible, how could I get the options ONCE per command and just compare when the current changes? I could add options to bot.autocomplete_options but is there a more dynamic way?
you can cache the results in interaction. extras
maybe use difflib.get_close_matches to get closes 25
yeah im doing that
ah true
thx i'll try that
so here if i put the hour as 23:25 (my local hour is 23:17), the bot will wait till the time is 23:25 to send the message, but if i put the hour as 6, for 6 in the morning the bot sends the message instantly
should i replace days=0 to days=1
is anyone able to help fix a Python code that i found for doing a webhooks bot, sadly the author isnt responding and i belive the syntax are broken and my understanding of script is rudimentary at best
Wh not just use the time kwarg on loop
i figured it out
Once I send my bot a users discord ID I want it to send it back how can I do this?
And it can’t be a command
Why keep the loop open like this...?
whats wrong with it? after it sends the message at the desired hour it doesn't loop again for 24 hours
for guild to get its 1st text channel id its :: id.append( guild.text_channels[0].id) but idk exactly about user
probably id.append(user.id)
But why would you need to sleep until morning?
well the whole point of that loop is to send the weather at 6am everyday
I just need my bot to send the id I sent to the bot back
how do i grab user input from a modal? i have everything else setup i just dont know how to do anything with their input
.vslue
*value
i dont really understand what you want to do, it wounds like a @bot.event and on_message()
!d discord.TextInput.value
The default value of the text input.
got smth mixed up anyways
guys does anyone know how to install pycord on spyder?
if I do pip install discord
I get this result
Note: you may need to restart the kernel to use updated packages.
C:\Users\Andrew\AppData\Local\Programs\Spyder\Python\python.exe: No module named pip
yo does anyone know how to run multiple discord accounts via one program
oh wait
py -3 -m pip install -U py-cord doesnt work?
you dont.. you just install discord.py
in spyder terminal?
in command prompt\
I need my bot to copy the id I send and then send the id back that’s all
threading or multiprocessing library
it worked but not on spyder
ye i kinda get that
I did but it doesnt work on spyder
but how considering bot.run only takes one token
spyder is an ide?
yes
bruh
modals
import discord, it says "No module named 'discord'"
Elaborate
ah i think i had this problem
quick fix
dont use spyder
or bot.wait_for

Wait for what tho
!d discord.ext.commands.Bot.wait_for
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**...
whats a free decent ide?
wait for message?
so i had this with discord, python installed it installed in the wrong file, and had to manually move it in the correct one
I only want it to respond to user ids
try pip3
but i can't really remember it was a few months ago
so how to fix that, like how u move the file in the correct path
you dont have to do that lol
just install it correctly
i found the answer on stack overflow , its where python downloads all the extensions that you import
i would love to tell you exactly where i moved the installed discord module but thats how i solved it
thks bro
so where did u move it?
@soft fjord run: pip list in your terminal
in spyder terminal?
you have it?
yo can anyone help me w running multiple accounts on one script on discord.py
i know threading would help
but idk threading that well
ye
well then it's not installed where it should be exactly
so how do I move it, and where?
for starters try pip uninstall discord
and install it again from command prompt and not spyder
AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?
forks like pycord use slash_command
without the bot?
disocrd.py uses app(lication)_command
bot.tree.command()
is your way go go in d.py
me?
yep
is there a limit to how many fields a modal has?
is it a slash command hto
4000
oh no wait
I thought you ment char limit
4000 fields
idk if there is a field limit
lol ok
🔥 crazy
prob tho
how u gonna have that many options lfmao
guess im testing that 4000 limit
gonna have to close your app to get out of my modal
is there a way to do multiple choice in one or just text based answers
async def restock(inter: discord.MessageInteraction, new_stock: discord.Attachment) -> None:
NameError: name 'discord' is not defined
import discord
i did
pip uninstall discord
ok
the docs dont state wether there is a limit or nit
*not
but the discord api is confusing anyways
*the dics
*docs
well im trying with 7 fields so ill lyk if its less than that lol
it's probably 5
@waxen cradle ```py
from datetime import datetime
from discord.ext import tasks
from discord.ext.commands import Bot, Cog
class MyCog(Cog):
def init(self, bot: Bot) -> None:
self.bot = bot
self.weather_loop.change_interval(time=self.get_next_date_at(hours=6))
self.weather_loop.start()
async def cog_unload(self) -> None:
self.printer.cancel()
def get_next_date_at(*, hours: int = 0, minutes: int = 0, seconds: int = 0) -> datetime:
dtnow = datetime.now()
if dtnow.hour < hours or dtnow.minute < minutes or dtnow.second < seconds:
dt = datetime(dtnow.year, dtnow.month, dtnow.day, hours, minutes, 0, 0)
else:
tomorrow = dtnow + timedelta(days=1)
dt = datetime(tomorrow.year, tomorrow.month, tomorrow.day, hours, minutes, 0, 0)
return dt
@printer.before_loop
async def before_weather_loop(self) -> None:
await self.bot.wait_until_ready()
@tasks.loop()
async def weather_loop(self) -> None:
...
@bulker.after_loop
async def after_weather_loop(self) -> None:
self.weather_loop.change_interval(time=self.get_next_date_at(hours=6))
alr thks, imma try this now
ill cry right now
I want my bot to say hello when I send the id of another discord user However I got this error
why are you using textchannel creation event for that
yea prob 5, its definitely less than 7
yeah, it's 5
gonna go cry now
now go cry 🔫

How is discord.Member.id an event
And waiting that long for a potential message is not the right way.
async def boost(ctx: discord.ApplicationContext,
AttributeError: module 'discord' has no attribute 'ApplicationContext'
did you mean commands.Context?
@waxen cradle You better look lol I've never done so much work.
is there an issue with that code?
It's perfect like all things should be.
||Dind't test it tough||
ah
It was from another question but he just slept the entire task for 24hrs and started the task wrong so it could be 10~ seconds off.
Critical time.

thx man i did, this is what i use now
consider using aiohttp instead of requests
^
?
also, requests.get returns a Response object which has a json method that does what're you doing for you (no need to json.loads)
Scratch that requests can wait for like an hour on some bad requests lol
oh yea there is no default timeout is there?
Not that I know of.
lmfao I wanna cry
Since it's sync it will just wait.
When they make a ticket via ticket tool I want my bot to send a embed then I want the user to send a id and my bot to send the same id back
my question still stands. Why aren't you just doing that inside the "ticket-creator" command?
#editors-ides sir
alr
Hey, does anyone know how to make a script that makes my account send a specific message to a discord channel every couple of minutes?
that is against tos
Discord doesn't allow self botting.
I'm not spamming though, it's for my private server
regardless
Alright, how do you make a script run over and over again?
^ We also won't help since it's a bannable offense.
We're not stupid.
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
What, I just need a way to make a script run over and over again.
Wym
Small specific guess but you already have a script that works but only runs once then closes.
Aeee nooooo...???
Again, we won't help break ToS.
you probably have a command that creates a new ticket, correct?
So please stop asking about self botting and anything regarding repeating scripts.
Is it not allowed to make a bot make an announcement every hour or a reminder?
I’m using ticket tool
I want the person making a ticket to just send the id of the person they are dealing and for my bot to just send the id back that’s all
Oh ok was just experimenting
Well no but we won't help break ToS, so we won't help with anything regarding this.
If you think that is unfair please contact @novel apex
keep in mind setting "message" as the event will return a discord.Message object if it meets the requirements in the check
But what requirements does a users id go under
Okay I luv you
you can check the message's content (to make sure it's an id), the channel, and the author
Can I get a example of the content thing
!d discord.ext.commands.Bot.wait_for you can get docs :)
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**...
check the first example
Is it the check?
wdym
odule 'discord' has no attribute 'ApplicationContext'
File "D:\yew\main.py", line 149, in <module>
async def boost(ctx: discord.ApplicationContext,
Oh nvm Alr I’ll try
Btw last thing yk what I can check like what should I check about the content tho to see if it’s a id if that makes sense?
if you're using slash commands, it's discord.Interaction
if you're using prefix commands, it's commands.Context
how do i get a users highest role without knowing what # it is? i can get the list of roles from interaction.user.roles[] but the highest role is at the end of the list
content.isnumeric() will tell you if all the characters of the string are numbers
module 'discord' has no attribute 'Option' what do i put for this
roles[-1]?
[:-1]
thanks
dpy doesn't have an equivalent of this
how do i fix it then
use a normal type hint
idk how
What is option?
discord.ext.commands.parameter(\*, converter=..., default=..., description=..., displayed_default=...)```
A way to assign custom metadata for a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")'s parameter.
New in version 2.0.
Examples
A custom default can be used to have late binding behaviour.
```py
@bot.command()
async def wave(ctx, to: discord.User = commands.parameter(default=lambda ctx: ctx.author)):
await ctx.send(f'Hello {to.mention} :wave:')
there's also param as an alias if you want
im confused on how i use it
there's an example in the docs
im like really new to python trying to learn as i go on
well that's not really good, discord bot development isn't really the most beginner-friendly project
But if you're determined it's fine
I did as well unless... no I still suck nvm
lmao
ik am fluent with 3 other langs but python
dpy's version changes it to a default instead of a type hint, and you gotta use commands.param(eter)
Not like this just typehint str then use describe decorator with the kwarg names for the arg.
read the docs for argument names and what they correspond
Could someone link the describe? I'm on phone rn
!d discord.app_commands.describe
@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.
Example:
```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
await interaction.response.send_message(f'Banned {member}')
``` Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
there's an options* decorator too iirc
Idk but sadly my power is limited right now 🗿
Bed.. too.. comfy
😴
Sleep rn
turn your phone off jeez
Just think about pandas always works for me
i still got tons of assignment left
Same but sleep important
File "C:\Users\Andrew\Desktop\discordbot.py", line 4, in <module>
bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
commands.Bot/discord.Client
I hate this library
meanie u beat me to it
bot = commands.bot()
ah
yup
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())
thats really all u need to put
bot = commands.bot()
NameError: name 'commands' is not defined
from discord.ext import commands
holdon
import discord
from discord.ext import commands
there
ile "C:\Users\Andrew\Desktop\discordbot.py", line 6, in <module>
@bot.slash_command(name = "main AI", description = "introduces himself")
AttributeError: 'Bot' object has no attribute 'slash_command'
💀
is the documentation wrong, cuz I copied it from there
k one sec
C:\Users\Andrew\Desktop>python discordbot.py
Traceback (most recent call last):
File "C:\Users\Andrew\Desktop\discordbot.py", line 7, in <module>
async def hello(ctx):
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\tree.py", line 889, in decorator
command = Command(
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 664, in init
self.name: str = validate_name(name)
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 211, in validate_name
raise ValueError(
ValueError: 'main AI' must be between 1-32 characters and contain only lower-case letters, numbers, hyphens, or underscores.
fixed this one
File "C:\Users\Andrew\Desktop\discordbot.py", line 10, in <module>
bot.run(os.getenv(token))
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 745, in start
await self.login(token)
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 577, in login
raise TypeError(f'expected token to be a str, received {token.class.name} instead')
TypeError: expected token to be a str, received NoneType instead
whats this?
is this correct? bot.run(os.getenv(token))
if ur getting it to connect to a diff file or u can do config.token
this line is loading the bot login token string from the system's environment variables
environment variables are a neat way to ensure privacy if your bot is open source
but if you're just keeping it to yourself might as well just have the token as a string then and there
so bot.run('token')
I did it
but the output was this
[2022-11-16 01:01:29] [INFO ] discord.client: logging in using static token
Traceback (most recent call last):
File "C:\Users\Andrew\Desktop\discordbot.py", line 10, in <module>
bot.run(token)
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 746, in start
await self.connect(reconnect=reconnect)
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 672, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x000001D933773790>
Traceback (most recent call last):
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
F
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
ile "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x000001D933773790>
Traceback (most recent call last):
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in del
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
RuntimeError: Event loop is closed
alright 2 things
first, not related to the problem itself
but in this server when you're going to send really long text
i urge you to use the pasting service
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
just so chat is clean and easy to read
now for the actual error you have: discord has these things called privileged intents, which are essentially switches that toggle what your bot can and cannot do
Read the error
Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
you probably have mentions to "discord.Intents" somewhere in your code
if you don't know/need intents you can remove that line
just do bot.run("")
otherwise you gotta go into the devpanel and enable the intents you want
alr thks
Traceback (most recent call last):
File "D:\BOTS\xiniu boost\discord\bot.py", line 1082, in invoke_application_command
await ctx.command.invoke(ctx)
File "D:\BOTS\xiniu boost\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "D:\BOTS\xiniu boost\discord\commands\core.py", line 134, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: argument of type 'int' is not iterable
show full error
code too
How are arguments passed on Discord classes?
Something like this: class Questionnaire(Modal, title='Questionnaire Response', test_list: list):
@fading marlinI mean it works with
def __init__(self, test_list: list): the thing is that it says Questionaire doesn't have custom_id.
full traceback?
site-packages\discord\ui\modal.py", line 201, in to_dict 'custom_id': self.custom_id, AttributeError: 'Questionnaire' object has no attribute 'custom_id'
is that everything?