#discord-bots
1 messages · Page 239 of 1
i have to take python in my degree of study for my bachelors
yeah my way of picking a random number was kinda shit
I'm realizing after seeing that message
Considering you are 2000 years old it's impressive that you are speaking
I haven't done this in 2 years either
hahahah born in 2000 my bad
nope born in the 70's
i just googled it hahaha had no clue otherwise
2007
where can i post a snippet of a program ?
sheeesh
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
discordpy is basically the same as twitchio
it was so relieving to see
are there any other platforms python has a similar module for
you coulda just pasted that here
import random
def generate_six_random_numbers():
numbers = []
counter = 0
while len(numbers) < 6:
random_number = random.randint(1, 69)
if random_number not in numbers:
numbers.append(random_number)
counter += 1
return numbers
!e ```py
import random
print(random.sample(range(100000), k=5))
@vocal snow :white_check_mark: Your 3.11 eval job has completed with return code 0.
[34131, 28189, 62461, 63624, 92476]
a shorter version
Hi 🐈
@vocal snow i like that. so everything i had was all wrong then
it wasn't wrong at all, just that random.sample is the shorter method
ok cool thank you
for whatever reason it didnt work for me
im using python 3.11 on a windows machine
!e ```py
import random
def generate_six_random_numbers():
numbers = []
counter = 0
while len(numbers) < 6:
random_number = random.randint(1, 69)
if random_number not in numbers:
numbers.append(random_number)
counter += 1
return numbers
print(generate_six_random_numbers())
@vocal snow :white_check_mark: Your 3.11 eval job has completed with return code 0.
[35, 19, 56, 8, 38, 49]
no
are you sure you're calling the function?
then i am doing something wrong, i thought i was
how do i call the function
which is what i was thinking with the def generate_random_numbers()
thats the definition
@vocal snowhow to make private interaction response
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
why isnt one of my command is not syncing when syncing it manually with a command as well as auto syncing. but my others are synced like give warn, search warn, remove warn, check warn but transfer warn is not syncing
How can i play adios with a discord bot
why tho?
you can do something like:
user = <userid here>
if user.guild.id == <guild id here>:
print('yes')
else:
print('no')```
its not js code btw
yes u can have a loop
for that
and this server is not related to javascript in any way
this server is not for javascript
go to some javascript servers
guild_id = 0
member_ids = [
123,
321
]
guild = client.get_guild(guild_id)
for member in guild.members:
if member.id in member_ids:
print(member)
How can i play audios with a discord bot
@reef gazelle are your looking for Red bot?
Well cogs are a thing for Red bot, not the Python bot
cogs aren't working for me for some reason
i had to write the whole thing in my main file
share your code
I cleared the whole thing
A website?
You can't run discord.js on a website
You need to use node.js
zeffo 
Learn how to use Node and Express in this comprehensive course. First, you will learn the fundamentals of Node and Express. Then, you will learn to build a complex Rest API. Finally, you will build a MERN app and other Node projects.
✏️ Course developed by John Smilga. Check out his channel: https://www.youtube.com/channel/UCMZFwxv5l-XtKi693qMJ...
this is the python server, please ask discord.js questions in their server: discord.gg/djs
This isn't really about creating discord bots but the python bot in this server is giving me blank messages. Anybody knows how to fix this?
what do you mean its giving you blank messages?
can I send a screenshot here?
yes
do you have embeds enabled?
should look something like this
ok lemme check
Hi
It's fixed now thanks
https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html
The command you were using was looking up documentation for a library called cog/cogs, the bot in this server doesn't differentiate based on what channel it's in. You would've wanted to do something like
(if it existed)
Thanks
How can i play audios with a discord bot
Thank you 🤦♂️
Cant access bot.latency from inside ping
using self.bot.latency but still
Dont think the bot is being passed in so treating self as the Ping class
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 490, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\Maja-Beta\bot.py", line 241, in on_application_command_error
raise error
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 890, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Discord\Maja Projekt\Maja-Beta\modules\voice\cog.py", line 45, in voice_join
audio_source = nextcord.FFmpegPCMAudio("audios\\moderator_call.mp3")
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\player.py", line 281, in __init__
super().__init__(source, executable=executable, args=args, **subprocess_kwargs)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\player.py", line 144, in __init__
self._process: subprocess.Popen = self._spawn_process(args, **kwargs)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\player.py", line 163, in _spawn_process
raise ClientException(executable + " was not found.") from None
nextcord.errors.ClientException: ffmpeg was not found.```
Calling an mp3 when its expecting a ffmpeg maybe?
Fixed needed to call ctx.bot.latency instead of self oops
have you installed ffmpeg and added it to PATH?
No, and how i made it on a hosting service?
which VPS are you using?
if its a standard linux machine you can install it from whichever package manager
No errors and the cog loads fine but the embed is not sending do I need to intent embeds or something?
How do i use that
@vocal snow```
Traceback (most recent call last):
File "C:\Users\KokoG\PycharmProjects\Logger\venv\Lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\KokoG\PycharmProjects\Logger\main.py", line 163, in clear
await interaction.response.send_message("Done",limit=amount,ephemeral=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: InteractionResponse.send_message() got an unexpected keyword argument 'limit'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\KokoG\PycharmProjects\Logger\venv\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\KokoG\PycharmProjects\Logger\venv\Lib\site-packages\discord\app_commands\commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\KokoG\PycharmProjects\Logger\venv\Lib\site-packages\discord\app_commands\commands.py", line 856, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: TypeError: InteractionResponse.send_message() got an unexpected keyword argument 'limit'
Can i play local audios without ffmpeg in a discord bot?
I’ve been having trouble registering my slash commands for my but using the py-cord library. What is the code I need to add to have my slash commands show up in the discord prompt when typing /
bump ^
Did you read the error?
dont think the cog is loaded properly cuz first red flags ppl generally have cogs and not Cogs directory second u shouldnt load cogs is on_ready use setup hook also its count += 1 and not = + 1
are u trying to purge a channel of messages
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
await interaction.channel.purge(limit=amount)
u need to sync ur commands
!d discord.ext.commands.Bot.tree
property tree```
The command tree responsible for handling the application commands in this bot.
New in version 2.0.
any reason u dont wanna use ffmpeg?
I’ll rename to just cog and try
In the console the counter is working but i’ll adjust
And setup hook do you mean calling the cogs setup method from the bot file?
whats the directory in which the cogs are kept?
show ur file structure
Cogs
send a screen shot
will do just in kitchen right now
I dont know how to use it at my hosting system
what hosting system?
i mean as long as u include ffmpeg.exe in same directory as root it should work right?
also after load_cogs() can u put this and show the output
print(bot.commands)
And how can he play a sound if he is already jn the vc
u just locate the sound file and create a ffmpeg object then vc.play
directly under or after the function
or where it’s called in on ready
under
Where did the vc come from?
!d discord.VoiceClient
class discord.VoiceClient```
Represents a Discord voice connection.
You do not create these, you typically get them from e.g. [`VoiceChannel.connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.connect "discord.VoiceChannel.connect").
Warning
In order to use PCM based AudioSources, you must have the opus library installed on your system and loaded through [`opus.load_opus()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.opus.load_opus "discord.opus.load_opus"). Otherwise, your AudioSources must be opus encoded (e.g. using [`FFmpegOpusAudio`](https://discordpy.readthedocs.io/en/latest/api.html#discord.FFmpegOpusAudio "discord.FFmpegOpusAudio")) or the library will not be able to transmit audio.
There is no inter.voice_client.play
!d discord.Guild.voice_client
property voice_client```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
audio_source = nextcord.FFmpegPCMAudio("audios\\moderator_call.mp3")
voice_client = await inter.guild.voice_client()
voice_client.play(audio_source)```
?
voice_client is property so you dont call it
Hello, I need help please with making a bar graph. Here is my code below and I am trying to set the x-axis as all the states and then the y-axis as the number of shipments. I'm not sure what to inser in the plt.bar() so it outputs just the names of the states and the values corresponding to them. I've been at this for hours ._. I am very beginner.
this is channel related to discord bots
go to #❓|how-to-get-help
Hey, I copy pasted some code that I found on overflow, but something is wrong, I tried to modify the code but I can't figure out what to change. Can someone help me please?
change @bot.event to @client.event
It seems to work now, thanks!
I have another question tho, do I have to invite the bot to each discord?
put print(bot.commands) under await load_cogs()
wdym? it needs to be in same server which has that channel to work
not loading
The point of the bot is to get the updates of a channel that is in another discord that doesn't have the "follow channel" option
then ur bot needs to be in that discord server too
Ohh, okay thanks!
Why is he playing 2 time audio_search_a
await inter.response.defer(ephemeral=True)
vc = await inter.user.voice.channel.connect()
await inter.guild.change_voice_state(channel=inter.user.voice.channel, self_deaf=True)
check_mark_png = File("pictures\\check_mark_maja.png", filename="check_mark_maja.png")
re_connected.set_thumbnail(url="attachment://check_mark_maja.png")
await inter.edit_original_message(embed=re_connected, file=check_mark_png)
audio_source_a = nextcord.FFmpegPCMAudio("audios\\maja_hello.mp3")
vc.play(audio_source_a)
while vc.is_playing():
await asyncio.sleep(5)
audio_source_b = nextcord.FFmpegPCMAudio("audios\\maja_soundboard_info.mp3")
vc.play(audio_source_b)```
can a message have multiple embeds?
@shrewd apex Still no luck can you assist?
Should I use bot.start instead and put in a main function
hmm
Some online say to use bot.start instead and a main function with asyncio.run to start the bot
Im not loading the load_cogs() at all right now
cause not sure where to be putting it
import asyncio
bot.setup_hook = load_cogs
async def load_cogs():
print("Loading cogs...")
for file in os.listdir('cogs'):
if file.endswith('.py') and not file.startswith('_'):
await bot.load_extension(f"cogs.{file[:-3]}")
print(f"Loaded {file}")
print("Loaded all cogs")
bot.run("token")
try this
check mine
i didnt add ()
ah yeh thanks
didn't spot that think it auto added
load_cogs is not defined
Done
Cause I put it above the function
mb yeah
Still doesnt look to be loading
Its finding it but not actually loading it in :/
wait
used the wrong prefix forgot I changed it to a ! been trying $ for a while ahah
💀
mfw ping cog
happens i effed up for like 1 hour yesterday where i constucted some nested matrix and committed a memory issue which gave wrong updates i spent like an hour+ to discover
copy.deepcopy to the save
I should prob take a step back into the basics for few days then go back to discord.py hahah
If I just put something random after prefix it tries to treat as a command and is throwing error but I had a check for CommandNotFound
If I just do like !1
add a check in the error handler
did you forget to include context and exception
!d discord.ext.commands.Bot.on_command_error
await on_command_error(context, exception, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this logs to the library logger, however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
Changed in version 2.0: `context` and `exception` parameters are now positional-only. Instead of writing to `sys.stderr` this now uses the library logger.
Yh was just needing ctx
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, CommandNotFound):
return
raise error
python 
my bad yoo
You can just say py btw
thanks
!code
😉
Should be working
Yeah it is now
I didnt have ctx before but it was working earlier or maybe I deleted some how
When it's sending 2 arguments it must accept both
So it could not work without ctx param
If I want to create additional folders under cogs directory so like ping is cogs/utility and I can have some in like cogs/fun
Do I have to modify the for loop or can I use like cogs/* for subdirectorys
You have to modify the for loop adding the extensions to go this one directory deeper
Little roll dice command
nice
If I am handling an error how can I stop it from still outputting to console am I doing something wrong?
where are you handling it
why do you have a cog and extension for each command
but it's because if needs to be replaced with elif
Just saw someone do it this way I know their kinda suppose to be separated into categories
same error
show your code now
@coinflip.error
async def value_error(self, ctx, error):
if isinstance(error, MissingRequiredArgument):
await ctx.send(f"{ctx.message.author.mention} Choose heads or tails!", delete_after=6.0)
elif isinstance(error, CommandInvokeError):
return
else:
raise error
weird
Dunno if do to with that "ignoring"
Due to a on_command_error in main file
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, CommandNotFound):
return
else:
raise error
I have this so cant just spam commands that don't exist if I remove it then the other handlers work and dont output to console but then you can spam console
any1?
Can you post a bigger section of the code
where's the elif..
So right now its handling commands that dont exist correctly but if I do like !cf without a choice then it errors but its still sending the error so dunno why its showing in console
I put the elif in and it didnt change
this is what it's doing now
the missingrequiredargument and the commandinvokeerror are two separate if statements
so it's just doing ctx.send and then raise error
yes but it's not stopping after that
Well you're not nesting them anyways
Can I just return under the await or is elif better then
elif is probably better
elif is better
Other errors are gone just this in console now
are you doing print(error) anywhere by chance
Ah yeh i pasted something else in before to try grab some more info
Need to modify this
What Im using so cant just do ! then anything like !1 !2
just do ```py
if not isinstance(error, CommandNotFoundError):
raise error
that fine?
forgot ctx put it back
commands.CommandNotFound
Working but now the coinflip spits error
if u just do !cf even tho it gets handled
but just fixed it before :/
I'm trying to understand what you're doing here: what commands are you running that cause the error? What is the correct way to run those commands so hey don't cause an error?
Im just running !cf so it sends a message "Choose heads or tails" so its argument is heads or tails
It gets handled but spits the error into console still
Well I can see you're trying to send an embed, but it doesn't actually get sent. So you can try writing a try-except around the different commands in the coinflip function to see what is causing the error
What error
recent screenshot
What's the problem
Just trying to handle errors for coinflip like not putting heads or tails.. or if the user inputs a number instead or if they put nothing at all
Given up goin to bed try again in few days aha
So buddy... let me explain this, so ip pingers are not consider as you may say "Illegealgwseh"
what
alirght BUDDY
do i user {user.mention} in dsicord.py to ping somone
How do I invite my bot to a server? (Help me idgaf if you're saying bruh behind the screen)
I think I got it hold on...
Go to the discord developer portal -> log in -> select the applications tab -> select your application -> go to url generator on the left sidebar -> select "bot scope" -> select required permissions -> visit the url displayed -> log in with your discord account -> pick the server -> press authenticate
Ok
how should i make a bot message in my account in time intervals
im confused at this part can somebody help me?
?
What do i add on here in order for it to work?
import discord
# Create a new client or bot instance
client = discord.Client() # or discord.Bot()
# Set the token
client.token = token
# Your bot's code goes here
@bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord!')
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content.startswith('!Ask'):
await message.channel.send('Hello!')
# Run the bot
client.run(client.token)```
nvm
help me with this bot
https://pastebin.com/SkE1Kedv
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
you need to enable message content intent
that code is very GPT-y
. or is there a limit for each?
no, can you show your code?
the one that not syncing?
yes
is the entire group not syncing or a particular command?
entire
4 other groups has the same name for the subcommand
you don't have a warn subcommand for this group
that was an example
got it, just making sure
I am basically talking about search and random subcommand
4 other groups has it too
are you sure the cog is loaded properly?
and you synced the tree after?
So back to what i fixed can be problematic, because if i remove the guild icon the config.icon will be None
and because the value will be None i can't check it like if config.icon and if config.icon is not None
Because basically it's a database value, and inside there is not like empty there still is a value which is None so that will break thru the check
As you can see i made a quick test to see if it's possible to check
Why is he playing 2 time audio_search_a
await inter.response.defer(ephemeral=True)
vc = await inter.user.voice.channel.connect()
await inter.guild.change_voice_state(channel=inter.user.voice.channel, self_deaf=True)
check_mark_png = File("pictures\\check_mark_maja.png", filename="check_mark_maja.png")
re_connected.set_thumbnail(url="attachment://check_mark_maja.png")
await inter.edit_original_message(embed=re_connected, file=check_mark_png)
audio_source_a = nextcord.FFmpegPCMAudio("audios\\maja_hello.mp3")
vc.play(audio_source_a)
while vc.is_playing():
await asyncio.sleep(5)
audio_source_b = nextcord.FFmpegPCMAudio("audios\\maja_soundboard_info.mp3")
vc.play(audio_source_b)```
import invite
Iirc there are issues with is_playing and it doesn't provide correct value. Try printing it just after starting playing
while vc.is_playing():
await asyncio.sleep(5)
``` what is this for
oh is it to sleep till the song is finished
just use the after parameter of .play
Generally to switch to next track you do that yeah
what's the issue?
So basically
example for discord Modal
When a server setups a welcomer using my bot if the icon gets removed after setup will destroy the build_embed config
But what i want to make is to send the welcomer just without the icon/banner
The reason the value is empty is because in database at first the value is null
So there is like a empty value that fucks up the check
Here i was trying to check
But in fact there's no icon URL
And i can't even check if the content startswith http or something because that would fail directly, it is empty
already tried
I also tried checking if guild icon is not true
is the icon supposed to be the guild icon?
Yep
does it really need to be in the database at all?
you could just store the guild id and access all data of the guild
no, you don't
How can you remember the color of embed?
if the icon is supposed to be the guild icon there's no reason to store it
How can you remember text on the embed?
I am not talking about those at all
Well yeah you are right about icon
just storing the guild id would allow you to get the guild via bot.get_guild, then access it's data
You are right but other images?
then it's a simple check to see if guild.icon is None or not
guild icon is just an example
But there can be set any images
as long URL is available
But in that case there already is a handler if it won't show up
My problem rn is if before guild icon was set
then removed, stops the entire embed build
So the real question is
How can i check if the value is empty?
Nvm im dumb, fixed
my bot is not creating a channel when i do the %create_channel command: https://paste.pythondiscord.com/gewuginiqo
whats the error?
its supposed to create a discord channel with the name of the survant and the survants choices whenever someone gives in the survey
but it does not
I meant the traceback in the console/terminal
this right now
I DIDDDD
wait see im hosting the bot code on a website
no erros and i took it to vscode and the terminal gave me some annoying stuff
maybe in line 79,
it should be channel = await guild.create_text_channel(name=channel_name, category=category)
you probably forgot the name param
what does that mean....
try adding a name= before channel_name in line 79
this
wait so you mean like install the .exe? or install the discord module to my python .311?
if you r hosting on replit, then they should have automatically installed discord py
oh yea
try this
channel = await guild.create_text_channel(name=channel_name, category=category) paste this in line 79?
yes
still not working
i also added the print here 1 thing right? see the code and when i do the %create_channel thing there is no "here 1" in the output console maybe that helps
i gave him the admin role
this the output
well on dc there is this "no module named " discord" thing
Can someone help me on this code
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
it didnt say hi
cuz u didnt installed discord in ur pc
its installed
yea im doing pip install discord.py rn
first of all, you imported discord twice.
second of all, add intents to your client,
third of all, remove .lower() from message.content
not telling u xd
ad an if statement
and match the ids
just do if statement
in the code
where u add the commands in the embed
no, matching the ids
if the author id isnt same as the dev id, it will not show the dev command
aight i got it to give out the same output as replit, but the create channel thing still does not work
breh, discord issue probably
wdym?
aight so i want it to be like a ticket system
can i tell you a scrt?
firstly tho, does the code make hypothetically snese?
that it posts the resulst
idk
import gspread
from oauth2client.service_account import ServiceAccountCredentials```
What are even these
Why do you have two error handlers
wait yes I didnt noticed he has two of them
At the line 81
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
return # Ignore command not found errors
You're overriding the previous handler and ignoring all exceptions
(you're not re-raising them)
oo, thats why I think why he has no errors
yea so what should i do
remove the 81 line's error handler
cuz u already have the correct one defined above
@unkempt mauve @naive briar just delete this?
Delete the whole second handler
imma be real wit you no idea what that means...
i used to code but now im mroe into video editin,...
delete the line 81's handler
how?
Delete the whole error handler at the line 81 to the line 84
now retry and give us error
no error
What's the code now
to be clear i deleted this
wait
yes
https://paste.pythondiscord.com/cimuqehoke
@naive briar
perfect
Then your survey_data is empty
when making a variable like money which holds money how do i store that?
open a json file ?
A database
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
item_info = {
'item1': 'This is information about item1.',
'item2': 'This is information about item2.',
'item3': 'This is information about item3.',
}
@bot.command()
async def info(ctx, item: str):
if item in item_info:
await ctx.send(item_info[item])
else:
await ctx.send(f'Sorry, I do not have information about {item}.')
This doesn't work for some reason when i do !info item1
(JSON isn't a database)
anyone know why?
do i need to learn sqlite now? x.x
like no inputs from anyone?
@naive briar if i want to host my bot on replit, do i need to post the code + json file and stuff on github first?
No
so it just has acces to the json file even tho its on my local pc?
anyone know why?
any error in terminal/output?
oh shit im an idiot @naive briar @unkempt mauve
there is a lot of errors
LOL
ValueError 😳
Enable message_content intent
nope the command just doesn't work
it was peace before the line 81's handler got removed
yea i just redebugged n it works fine
Maybe
tbh, that too much errors moment was so funny
ur reaction lol
i almost died
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
item_info = {
'item1': 'This is information about item1.',
'item2': 'This is information about item2.',
'item3': 'This is information about item3.',
}
@bot.command()
async def info(ctx, item: str):
if item in item_info:
await ctx.send(item_info[item])
else:
await ctx.send(f'Sorry, I do not have information about {item}.')
Like this?
Don't ask me just try
Hi me just try

Thank you it's working now, why did i have to enable the intent?
wait omg its actually errors @naive briar @unkempt mauve those happen when i do the %create_channel command
So your bot can access messages' content to process the commands
so u need to fix your code
and ask us if u r facing problems
oh man.
how difficult is sqlite in comparison to python?
well it says it is missing files
ah right thanks!
if i said something stupid pls dont kill me
add those files
kk into one folder?
It's very easy
see where they want the files to be in
Cause if you don't your bot does not see messages meaning prefixed commands doesn't work
oh really? ima give it a try then
ye thanks
thanks
https://sqlbolt.com/ is a good place to start
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
oh
oh wow this is actually good
can someone give me a code that sends an embed when i say the word?
Btw is there any way to put what the bot says anything that the bot says in a simple box
like this
@naive briar @unkempt mauve fixing the code 1by1 encountered a stopping point, what does that mean?
Yes you do that as normal
Just put the value to send in backticks
ah right thanks!
would it be easy doing something like this?
how to make me discord bot if i say hi it will say hello.???
are you using discord.py?
Nothing more than just copy paste text and put in embed
pls can someone help me ?
Traceback (most recent call last):
File "/home/debian/t.o./main.py", line 367, in <module>
discord = Discord()
File "/home/debian/t.o./main.py", line 30, in __init__
self.songs = json.loads(f.read())
File "/usr/lib/python3.9/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.9/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.9/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Unterminated string starting at: line 5970 column 9 (char 196579)
there is only 376 lines in my script 💀
well the error is coming from the json file so why are you checking the script
can u give me an example?
Example of what
of hthe embed
the and how to make it look like the screenshot i gave you above
huh ?
that's the 5970th line ...
!d discord.Embed
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...
Thanks, also would it be possible for the output to change it's value based on an excel spreadhseet on google classroom
i need help check #1106969721343049778 for infor
If you connect it then why not
how would you do that is there any youtube videos to it?
Never connected to excel using python so no idea
You need to look on the internet for that
pls can someone help me ?
Traceback (most recent call last):
File "/home/debian/t.o./main.py", line 367, in <module>
discord = Discord()
File "/home/debian/t.o./main.py", line 30, in __init__
self.songs = json.loads(f.read())
File "/usr/lib/python3.9/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.9/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.9/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Unterminated string starting at: line 5970 column 9 (char 196579)
Show lines above and below it
json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)```
Deserialize *fp* (a `.read()`-supporting [text file](https://docs.python.org/3/glossary.html#term-text-file) or [binary file](https://docs.python.org/3/glossary.html#term-binary-file) containing a JSON document) to a Python object using this [conversion table](https://docs.python.org/3/library/json.html#json-to-py-table).
*object\_hook* is an optional function that will be called with the result of any object literal decoded (a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict")). The return value of *object\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders (e.g. [JSON-RPC](https://www.jsonrpc.org) class hinting).
*object\_pairs\_hook* is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of *object\_pairs\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders. If *object\_hook* is also defined, the *object\_pairs\_hook* takes priority.
if you're using the json module with a discord Bot - depending how you're running its functions - that's not a good idea
need help the error code and the code itself: https://paste.pythondiscord.com/akasocoweg
What's the code right now?
But this is not even related to discord bot
wym ?
it is?
What have you tried so it's showing the error
json.load
instead of json.loads
you're receiving a 404 Not Found response from the google API
its a discord bot to post the google spreadsheet info in a newly created channel
The error itself comes from gspread
@jovial patrol
What did you put inside
bump
how would i fix that? i done set up a cloud proj with google sheets api and got the credential.json in the code tooo
i just changed the loads by load and nothing else
but it's working on my windows machine
It takes file object not it's contents
and i receive this error only in my linux vps ...
So f instead of f.read
okok
idk, i've never used the google api
🤫
Something to ask in #1035199133436354600
Not in a discord bots channel ^-^
i did, nobody replies tho :/
aksed on forums aswell
bro's trying to destroy his event loop
Traceback (most recent call last):
File "/home/debian/t.o./main.py", line 367, in <module>
discord = Discord()
File "/home/debian/t.o./main.py", line 30, in __init__
self.songs = json.load(f)
File "/usr/lib/python3.9/json/__init__.py", line 293, in load
return loads(fp.read(),
File "/usr/lib/python3.9/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.9/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.9/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Unterminated string starting at: line 5970 column 9 (char 196579)
good point, but doesnt the thread get deleted after a while?
Really weird
After 30 minutes of inactivity
so youre suggesting i just go back and write something every 30 mins?
I suggest you include actual error in title and tags and not discord bots
So somebody who worked with Google api can help and not somebody who knows discord bots
right yea, is there a way i can change the title?
Close and make a new one
cooldown
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.
When you close current you can create new one
oh aight ty down
https://paste.pythondiscord.com/duhebodidu - This is my code, the item info seem to be taking up ALOT of space in my main.py is there any way i can move this code to another folder just for storing the data? And also would it be possible to categorise the items?
no it doesnt work...
yes but does it really affect people around me? it's not like i'm trying to help people with chat gpt
@fierce crag
you can ping the mods all you want or use @novel apex
but it on the rule chat gpt doesnt provide you the accurate code
i doubt they would care especially when i'm just trying to figure out how to do something
and? does it matter to anyone expect me? I'm trying to figure out how to implement excel spreadsheeet data into my python code therefore i asked chat gpt it's not like i'm helping a person with chat gpt
chat gpt doesnt really help you
unless I ask asking to code for me about if i say hi and he will respond hello it doesnt even work (dont react quickly i have installed discord)
what does that have to do with me breaking the rules?
how did you close it?
i left it and spammed "CLOSE POST" but it would not close
its fine tho cuz cooldown over
...
you are supposed to run !close
oh lmaoo
in it
my bad
@commands.command()
async def help(self, ctx):
select = Select(options=[
discord.SelectOption(label="Moderation", emoji="", description="")])
view = View()
view.add_item(select)
await ctx.send("**Help Below**", view=view)``` the menu won't send it will only send the jsk extension help command?? and ik i have description empty bc im not done
gets you banned
still haven't answered my question how does me using chat gpt to help myself mean i'm gonna get banned?
you make no sense
Kinda stupid to ask but have you even replaced the placeholder names with yours
!rule 10 only applies when someone uses ai tools to help others
on your own you can do whatever you want so pinging mods is pointless there
i lit tried explaining it to him he to stubborn to admit hes wrong
ofc i did, removed them for privacy stuff as its tokens and stuff
its also bannable
??
like i said it is when the person uses it to provide help in the python discord but using it on your own has nothing to do with this server
he just copy and paste it/ or taking photo
period
i wouldn't really argue if i were you considering you have been in this server for 2 days
doubt you would know anything
mad
taking screenshot now
naw

mmm
this is #discord-bots so if you have something to talk about move to dms or elsewhere @lean harbor@slate swan

Hello everyone. For my first python project I wanted to create a discord bot. But I keep running into errors that I don't know how to fix. Can someone make me a direct message so I can explain the issue? I don't want to spam the python help forum or this chat with my newbie problems
Making a help post is completely fine
whats the problem?
Why would you want to do that?
I was trying to make a roll bot for a TTRPG to roll different random things. I thought it would be a smart idea to split the main.py with cogs to cog_rolltables.py and then my database randomrolls.yaml.
Now no matter what I do, when I try to run it on replit.com it keeps giving me an error or nothing at all happens and the console just says "cog_rolltables.py" but nothing more
from item_info import item_info
So you put your command in another file
i did it the other way around thanks!
`import discord
import os
import asyncio
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=',', intents=intents)
token = os.environ['TOKEN']
Load Cogs
@bot.event
async def on_ready():
await load_cogs()
async def load_cogs():
for filename in os.listdir('./Cogs'):
if filename.endswith('.py') and filename != 'init.py':
await bot.load_extension(f'Cogs.{filename[:-3]}')
print(filename)
@bot.command()
async def load(ctx, extension):
await bot.load_extension(f'cog_rolltables.{extension}')
await ctx.send(f'loaded {extension}')
@bot.command()
async def reload(ctx, extension):
await bot.load_extension(f'cog_rolltables.{extension}')
await ctx.send(f'reloaded {extension}')
@bot.command()
async def unload(ctx, extension):
await bot.load_extension(f'cog_rolltables.{extension}')
await ctx.send(f'unloaded {extension}')
Run the bot
async def main():
async with bot:
await bot.load_extension('cog_rolltables')
await bot.start(token)
Run the bot
async def main():
await bot.start(token)
print("Bot has started successfully!")
Run the main function
if name == "main":
asyncio.run(main())`
And my cog_rolltables code:
`import discord
from discord.ext import commands
import random
import yaml
class Rolltables(commands.Cog):
def init(self, bot):
self.bot = bot
# 1 BUILDING TYPES
@commands.command()
async def Building(self, ctx):
# Load the YAML file containing roll tables
with open("RandomRolls.yaml", "r") as file:
roll_tables = yaml.safe_load(file)
# Check if the roll tables exist
if roll_tables:
# Roll on each table
table1_result = random.choice(list(roll_tables["1_Building_Type"].values()))
table2_result = random.choice(list(roll_tables["1_Building_Feature"].values()))
table3_result = random.choice(list(roll_tables["1_Quirky_Style"].values()))
table4_result = random.choice(list(roll_tables["1_Quirky_State"].values()))
table5_result = random.choice(list(roll_tables["1_Quirky_Feature"].values()))
table6_result = random.choice(list(roll_tables["1_Quirky_Secret"].values()))
# Construct the final message
message = f"You see a {table1_result} that is {table2_result} with a {table3_result} style and {table4_result} look. There are {table5_result} and a secret {table6_result}."
# Send the message as a response
await ctx.send(message)
else:
await ctx.send("Table not found.")
async def setup(bot):
await bot.add_cog(Rolltables(bot))`
Uhh why do you have 2 main()
oh ... that slipped me because I copied the code back from a debugger
Did you try reloading the extension with your message command first?
I can't even get the bot to connect to my discord. replit is throwing error messages at me and stops the script
!code
Traceback (most recent call last):
File "main.py", line 47, in <module>
asyncio.run(main())
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
return future.result()
File "main.py", line 42, in main
await bot.load_extension('cog_rolltables')
File "/home/runner/SRTTRPGDISCORDBOT/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1011, in load_extension
raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'cog_rolltables' could not be loaded.
KeyboardInterrupt
It's an import so you cannot just make up a name.
If your rolltables.py is in a folder called Cogs
Then it should be Cogs.rolltables
Use Cogs.rolltables
I'd love to be able to use cogs, so I can create different functionality in a plug-and-play style. But I am too much of a newbie to deal with cogs it seems. I am sorry if I ask stupid questions that might be obvious for you guys.
The cog_rolltables.py is in a folder called Cogs on Replit
There are no stupid questions.
Not cog_rolltables or anything
I renamed cog_rolltables.py to Cogs.rolltables.py and adapted the code but still get error messages:
import os
import asyncio
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=',', intents=intents)
token = os.environ['TOKEN']
# Load Cogs
@bot.event
async def on_ready():
await load_cogs()
async def load_cogs():
for filename in os.listdir('./Cogs'):
if filename.endswith('.py') and filename != '__init__.py':
await bot.load_extension(f'Cogs.{filename[:-3]}')
print(filename)
@bot.command()
async def load(ctx, extension):
await bot.load_extension(f'Cogs.rolltables.{extension}')
await ctx.send(f'loaded {extension}')
@bot.command()
async def reload(ctx, extension):
await bot.load_extension(f'Cogs.rolltables.{extension}')
await ctx.send(f'reloaded {extension}')
@bot.command()
async def unload(ctx, extension):
await bot.load_extension(f'Cogs.rolltables.{extension}')
await ctx.send(f'unloaded {extension}')
# Run the bot
async def main():
async with bot:
await bot.load_extension('Cogs.rolltables')
await bot.start(token)
# Run the main function
if __name__ == "__main__":
asyncio.run(main())```
Nonono
With the error message:
Traceback (most recent call last):
File "main.py", line 47, in <module>
asyncio.run(main())
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
return future.result()
File "main.py", line 42, in main
await bot.load_extension('Cogs.rolltables')
File "/home/runner/SRTTRPGDISCORDBOT/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1011, in load_extension
raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'Cogs.rolltables' could not be loaded.
Just name the file rolltables
But idk why you are hard coding it if you already have a function that takes all the cogs.
I've been trying so many solutions until I didn't understand it properly anymore. I read on stackoverflow the code of someone who made it work and tried to copy and ended up with this
Is outdated tough.
Well other than the add command not awaited not much
I'll think I will just start from scratch and work my way to a working code piece by piece and delete all the things I saw on Stackoverflow. I can't get it to work. Thanks everyone anyway for all suggestions
' ': '__** [ ~ Info Command ~ ]**__ \n`Description: Allows you to search up information and trade value of a specific item. \nNote: You need to type the exact name of the item with no capital letter. If it is 2 words or more use a underscore(_) instead of a space. \nUsage: !info [item name] \nExample: !info pumpkin_fedora `',
why does this not work? I did !info and it did nothing
import os
import logging
import asyncio
import discord
from discord import Intents
from discord.ext.commands import Bot
from discord.ext import commands
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
class AwesomeBot(Bot):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
async def load_cogs() -> None:
for filename in os.listdir('./Cogs'):
if filename.endswith('.py') and filename != '__init__.py':
await bot.load_extension(f'Cogs.{filename[:-3]}')
logger.info(filename)
@staticmethod
def on_ready() -> None:
logger.info("I'm online!")
def setup_hook(self) -> None:
await self.load_cogs()
async def main() -> None:
intents = discord.Intents.default()
intents.members = True
bot = AwesomeBot(command_prefix=',', intents=intents)
async with bot:
await bot.start(os.environ['TOKEN'])
# Run the main function
if __name__ == "__main__":
asyncio.run(main())
Could you show the whole command?
wdym
import discord
from discord.ext import commands
from item_info import item_info
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.command()
async def info(ctx, item: str):
if item in item_info:
await ctx.send(item_info[item])
else:
await ctx.send(f'Sorry, I do not have information about {item}.')
thats it and in item info i just have similar codes to what i sent above which works.
And this doesn't work?
yep not sure why
Do other commands work?
yep
discord.ext.commands.errors.MissingRequiredArgument: item is a required argument that is missing.
an error
That means you didn't provide an item in the command.
but it's just !info
theres no item to provide.
oh you meant, but that doesn't make any sense. since the line of code that i gave you is in a py file called item_info
i imported it to the main.py
I mean you have it there in the function but you still ask for an item. What do you want/ expect to happen?
when i type !info it shows me how to use it
it's supposed to be used like this:
!info [item name]
Oh okay, well why not use the error handler that discord.py has build in?
Otherwise you would need to do that for every new command.
I don't know how to use it lol
But the problem now is figuring out why this code doesn't work btw @cloud dawn you know a way to infinitely keep a bot online which website do you recommend
Because it will never go in the command. You can do it all manually but you'd need to do it for every command.
As for hosting a good vps is around 5 bucks.
aight thx
You'd need to do this ```py
@bot.command()
async def info(ctx, item: str = None):
if item in item_info:
await ctx.send(item_info[item])
else:
await ctx.send(f'Sorry, I do not have information about {item}.')
Now it's an optional argument.
alright thanks
Though it still doesn't work.
Sorry, I do not have information about None.
thats what it says
Then it works right?
That's what you made right now, you can expand it but like I said it's very manual. Exmaple:
@bot.command()
async def info(ctx, item: str = None):
if not item:
await ctx.send("Please provide an item or put general info here or smth")
elif item in item_info:
await ctx.send(item_info[item])
else:
await ctx.send(f'Sorry, I do not have information about {item}.')
shouldn't it be type hinted as Optional[str] then
And return None and be indicated as not to call function and use the name kwarg instead of the function name and use the discord command handler
yes
But you shouldn't use it.
why not
@bot.command(name="info")
async def _info(ctx, item: str | None = None) -> None:
if not item:
await ctx.send("Please provide an item or put general info here or smth")
elif item in item_info:
await ctx.send(item_info[item])
else:
await ctx.send(f'Sorry, I do not have information about {item}.')
Well it's a function you should not call standalone so yes I'd use this in production.
What would you do?
if naming the function the same as what you want the command to be invoked as is impossible (i.e. using illegal characters), or would cause a namespace collision with other variables you've defined, then the name= kwarg would be necessary, otherwise its merely preference
Indeed but if I'd be working on it with multiple people I'd enforce the underscore.
then thats your style convention, i.e. preference
Omw pr on black
that's different from just correcting the type hint
I mean the above is correctly typehinted
It's either a string or None
you didn't type hint ctx either, and black does not enforce naming conventions
who says they cant? 
what a battle
The child lost as usual
lmao
I can't really say who "won" but if it's a tie we're teenagers.
💀

lol
im trying to make a simple game using buttons on dpy and i cant figure how to make thing i wanna wait_for a button press but idk how???
wait_for? Buttons have a timeout.
Here is an example.
ok
@vivid axle What is important here is that you just need to make the View then use it in the command.
where should i make the class for confirm because i need to use a class that is already created inside the commadn
You can put it outside the cog class
i need to use a class that make inside the command tho?
I don't exactly know what you mean.
https://paste.pythondiscord.com/axisuxoseg - is there a more efficient way to do this? if so could you please send an example?
i have a class i made
and i make a instance of it in the command which i need to run a function on with the game
Please use one channel and have some patience before reposting.
alright thanks
lol
Not really but a cleaner way would be to use a json file and load it when the bot launches.
i managed to get it to work, but im edititng the message i send with the view, but how can i stop it from saying interaction failed when i press the button?
aight thanks
After you press a button you could either remove it or keep it active.
confused
After sending the edited message you can pass an empty view or a new ione
oh
why pass in a view at all
just do view=None
im so confuse
show your code
hold
why are you defining the view inside the command
what does that mean
class e:
def cool(self):
return 'hi'
def hello():
a = e()
class fortnite:
def hi(self):
print(a.cool())
fortnite.hi()```
like that but fortnite is the view
this is so confusing
i wish it was less complicate 😭
no
you don't need an inner class at all
you're not using a at all in your btns class
i give up
Hey could anyone please tell me how I can make an input option, optional in a slash command
what lib do you use?
just set default value as None then
Sorry how do I set the default to none here?
@app_commands.describe(message_to_send = "Please enter the message you'd like to send out.", reply_id = "Please enter reply ID if applicable.")
not here thats the decorator
you set it in the function signature
Oh so I just make this
async def sendmessage(interaction: discord.Interaction, message_to_send: str, reply_id: str):
This
async def sendmessage(interaction: discord.Interaction, message_to_send: str, reply_id: None):
yeah that's an error nvm lol
no
: str is a typehint
you need to add default value
so something: str = None
and to be fully correct with typehints you should do this: something: str | None = None
what are some util commands I should add to my bot
Thank you so much it works
my discord bot it not working for one person in perticular
like not even his alt can preform any functions
how do i fix this
(ping pls)
#❓|how-to-get-help
try to give us as much info as possible in 1 message
i created a bot. everzone else can preform functions exet for this one person, no matter the account he can not use the bot
it just doesnt work for him
that's not much info tbh
https://www.pythondiscord.com/pages/guides/pydis-guides/asking-good-questions/
.
thats all that the problem is
i tried copying same perms as the other bot that worked
and noting happend
it works for everyone else
like every other account
can preform functions ok
other then this person
so he's typing commands in your guild and the bot doesn't respond to it?
yes
do you have an on_message event in your bot which proves it can actually read when the user sends a message?
you also haven't provided any code yet, which is basically me guessing the issue
no matter the code
any code doesnt work
for this one singular dude
who is "everyone else"? just some other members in your guild with the exact same roles and permissions as your "victim"
all other people on all other servers
no matter roles nor server
are you sure he's actually a friend and not just trolling?
ive known him for 4 years
show me your on_message and a proof your bot can't read whenever this person sends a message in a channel (but DOES when you or someone else does)
hey where i can find good source to learn py boot in discord?
https://realpython.com/how-to-make-a-discord-bot-python/ this guide is pretty good, just make sure to specify bot intents because it's a bit outdated
thx for u 😍
How to use embed for discord bot messages?
create an instance of discord.Embed and pass it to the embed kwarg
Will It work if I've got a list of item info which is in square brackets name a variable
Will it work if I just .embed the name of the variable
what
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.
https://paste.pythondiscord.com/hatuxabaze will it work if i just embed the item_info
how would i embed item_info
what do you mean "just embed the item_info"
all the stuff in the variable item_info
I told you, create an instance of discord.Embed and add the content in it as you choose
!d discord.Embed
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...
embed = Embed(title="Item Info", description="Some text")
await ctx.send(embed=embed)
you can add fields with embed.add_field
you can check the other methods in the doc
thanks
im not really sure what you mean.
for what I see you should use a field
perhaps multiple embeds as there could be more than 25 items
i'm really new to this, so i'm not quite sure what you mean
i've got loads of items which each line is basically 1 command (E.g !info [item])
and i've got about 30 different items which all need an embed
how would i do that?
yes, then the output would be the rest of the info
and yes i want to embed the info, with maybe a picture and maybe a link in the title which links to the wiki
I have been doing that lol
lol how did you do it
so this works except you change the title to the parameter representing name of the item and description be the string you get from dict
you mean the 'Embed' i change it to item_info?
isn't there a module which i need to install?
no
How can I remove some administrative commands from the help section?
i am
Embed is actually discord.Embed if you mean by that
you can set hidden to True in the command decorator
line 18
i should i replace the item_info with the embed?
yep. And theres an error.
what's the error then
TypeError: unhashable type: 'dict'
uh
i don't think this will actually work as intended. Because the user is supposed to do !info (item)
but how will the bot know which item you are supposed to do
that's in the command parameter
if i pass the item input thats not what i wanted it to do
you build the embed based of it
?
idk what you want then
do you want to show all items or only a single item
since the user will choose which item info they wanna look up and i ONLY want it to show the single item they look up
not the whole dicitionary
yes then put line that defined the embed inside the command function
and use item instead of item_info
eh how would you..
as i said lol i'm very new.
move that line into the if statement
why would that make a difference
if item in item_info:
embed = Embed(title=item, description=item_info.get(item))
await ctx.send(embed=embed)
lemme see if this works
why does it do that?
ive only sent it once
you have another ctx.send() before the embed was sent
@bot.command()
async def info(ctx, item: str = None):
if item in item_info:
embed = Embed(title=item, description=item_info.get(item))
await ctx.send(embed=embed)
else:
await ctx.send(f'Sorry, I do not have information about {item}.')
i'm confused what you mean.
aight
OH WAIT i know why it's because im using replit for my bot to be online 24/7
i need to update that code lol
works thanks!
Hello I’m making a verify command and I keep getting this error and I don’t understand
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
guys why this code didnt say hello to me when i say hi https://paste.pythondiscord.com/emicayeloc