#discord-bots
1 messages · Page 126 of 1
hm there's railway.app that can host a pgsql mysql or mongodb server for you
any tutorial?
you wanna learn how to use a database
or you already do and want to host one
https://sqlbolt.com you can use this to learn sql
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
i already know how i just need to host
and then use any you want to
well then just go to https://railway.app you'll understand everything yourself while you;re at it
aight thanksss
My extension fails to load, and I don't get any errors. Any ideas why?
How do i make a changing status loop?
cogs extension?
do you have any error handler? @event async def on_error
!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").
Tyyy
Nope, I don't think so.
ie = []
for i in os.listdir("./cogs"):
if i.endswith(".py"):
ie.append("cogs." + i[:-3])
if __name__ == '__main__':
for ex in ie:
bot.load_extension(ex)
bot.loop = asyncio.get_event_loop()
bot.loop.run_until_complete(_startbot(bot))
a = '\n'.join(i for i in bot.extensions)
print(f"Loaded Extensions:\nNote that there should be:\n- modmail\nList:\n {a}")
Then in the terminal:
Loaded Extensions:
Note that there should be:
- modmail
List:
-------------------------------
You are logged in as Testing#3233!
And the default help message only says this: Nothing about the modmail cog.```
No Category:
help Shows this message
Type >help command for more info on a command.
You can also type >help category for more info on a category.
What the
first of all check if the ie list contains something, maybe it doesn't find the directory
then add your extensions with this code, it will help with errors:
for cog in cogs: #cogs is the list where extensions are stored
try:
print(f"loadin {cog}")
bot.load_extension(f"path/to/cogs/{cog}")
except discord.ext.commands.NoEntryPointError as e:
print(f"Ignoring exception in loading cog: {cog}\nNo setup found", file=sys.stderr)
traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)
except discord.ext.commands.ExtensionFailed as e:
print(f"Ignoring exception in loading cog: {cog}\nThe extension or its setup had an execution error", file=sys.stderr)
traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)
else:
print(f"{cog} loaded")
remember to import sys and traceback
Or just let default logging handle it
why make all this unnecessary code
Your cog/extension loading is outdated
just because usually you will put an error handler somewhere at some point 
It worked an hour ago tho
probably bc you updated dpy
and that is nicer than the default logging
How so?
Your extension loading is also outdated btw
well nope, not for disnake 
I haven't updated anything, it worked, I changed some code in another file, I restarted the bot, and it didn't work.
I'm using py-cord too
Found the problem
It didn't give me an error, but when I printed the result it contained the error. 🤷♂️
lol
that's why this is handful
a = bot.load_extension(f'cogs.{filename[:-3]}')
print(a)
```Gave this in console```
{'cogs.modmail': ExtensionFailed("Extension 'cogs.modmail' raised an error: SyntaxError: positional argument follows keyword argument (modmail.py, line 46)")}
Another one, what does this means?```py
{'cogs.modmail': ExtensionFailed("Extension 'cogs.modmail' raised an error: SyntaxError: EOL while scanning string literal (functions.py, line 16)")}
The errors are in your modmail file, line 46 and functions file, line 16
But if I have an error in the functions file, why doesn't the modmail file load? The error didn't show up in console at first, and the bot still starts.
loading cogs doesn't stop the bot from starting, it will just run without the extension
and it can be because your modmail use some methods of the functions file
bro, what is the order system for the voice channel?
join to create position is 69 and 384 position is 72
for i in range(len[feilds]):
a = feilds[zer]
a.split(':')
ke = a[0]
val = a[1]
embed.add_field(name=ke, value=val)
zer = zer + 1
in this i am trying to get data from a dict and send it in feilds of embed
dict = {em_feilds{key 1:" hi this is key 1 ",key 2:" hi this is key 2"}}
this is what i am trying to send but it shows me error :
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'builtin_function_or_method' object is not subscriptable
this is the error i am getting
!e
print[0]
@primal token :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: 'builtin_function_or_method' object is not subscriptable
I also recommend checking out the example in https://docs.python.org/3/glossary.html#term-Pythonic
How can I send all errors to a text channel? Using on_command_error I only get the errors in commands, not the ones like missing permissions and events stuff.
how to make my bot send embed messages?
i am working on that only
so yk how to do it?
can you tell me the basics please?
its easy if u know how to make bots
i learnd it from api
how much do you have already?
starting from scratch or a working bot
starting from scratch
but I am not new to python overall
Take a look at the basic example first https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py
ty peeps
If sending messages is all you want to do
Check out webhooks
ik those
I used them before
I want embed messages to make my bot seem more clean
why is it sending it twice
?tag twice
This is not a Modmail thread.
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.
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.reply("❌ We dont have that command ! Try using !help")
else:
raise error```
?
Did you read what I sent?
i did not understand
Didn't understand what
embed = discord.Embed(colour= discord.colour(to_rgb(r, g, b)), title= "!")
It dont work
to_rgb
How does it not work
^
what..
Why are you using to_rgb
You should be using the from_rgb class method of discord.Colour
Why only to_rgb?
from_rgb is a classmethod of discord.Colour
I strongly recommend you familiarise yourself with oop
ITS GETTING WORST WHAT
so, do you have multiple instances of the bot running?
How do you know?
also i have that command
bc i turned my hosting off
what is going on
do i need to update my vscode?
Vscode??
What is your hosting
visual studio code
say_msg: str = None??
That's the default value
nextcord is a fork of discord.py
also if you want parameters just use bot.tree.commands for slash commands
it's easier and looks cooler
im using nextcord
Uh huh looks very trustworthy and good
if you need further help with discord.py join gg/dpy
i know them
like they have a lot of customers
ill try to open a ticket
maybe they could help
all I want to say is that if you made /say a slash command it would be easier since you only have one parameter and looks better
Their website doesn't even exist yet
yes ik
so do mine
but the hosting
idk maybe its bc of them
yes
That's an editor-
then it will show an error message in the terminal if it's because of them
???
your editor has nothing to do with the hosting
There wouldn't even be an error in the case
If the bot is not online and you use a slash command it will show an error
Guh!?
Cool?
Who asked though
That's completely irrelevant
ok its a problem w my code
i reset the token
so these are my packages
import nextcord
from nextcord.ext import commands, tasks
from nextcord import Interaction
from nextcord import File
import asyncio
from nextcord.ext.commands import cooldown, BucketType
from nextcord.ui import Select
import datetime
import random
from datetime import datetime, timedelta
from nextcord.abc import GuildChannel
from nextcord import slash_command
import humanfriendly
import calendar
from random import randint
import os
maybe some of them got updates?
like w the packages
@slate swan have you loaded the extension/cog that command is in? That's the only reason it wouldn't be being registered
yes
def setup(bot):
bot.add_cog(commands(bot))
and you're running bot.load_extension("your_ext_name") in the main bot file?
for fn in os.listdir("./cogs"):
if fn.endswith(".py"):
bot.load_extension(f"cogs.{fn[:-3]}")
Hmm, not sure then, probably worth joining the nextcord server for help on it, there's a help channel system there with lib-specific knowledge
yes theyre trying to help
its so weird
should i do that
i did
and still doesnt work
??
you're probably running the code multiple times
im not
reset your token and retry, that might help
send me the code
i already did
ill try again
hmmm, are you hosting the bot?
yes but i closed it also changed tge token again
now its sending twice
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Noas Bot\main.py", line 155, in on_command_error
raise error
nextcord.ext.commands.errors.CommandNotFound: Command "sadfhgsay" is not found
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Noas Bot\main.py", line 155, in on_command_error
raise error
nextcord.ext.commands.errors.CommandNotFound: Command "sadfhgsay" is not found```
in the terminal and in the server
may i see the code?
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.
oh god
what
what command is causing the problem?
do you have any on_message events/listeners in other files?
and what about on_command_error, just that one in your main script?
ah ok, so no others
no others
then its possible one of your on_message listeners is processing the commands twice
oh wait i do
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
embed = "You have cooldown ! Please use this command again in {:.2f}s".format(error.retry_after)
await ctx.send(embed)
else:
raise error
ah i thought you meant you had deleted that one
well either way 0 or 1 on_command_error is fine
oh okay
should i send them?
does any of your listeners have a await bot.process_commands(message)?
ill check
No
wait, so this was the on_command_error you had deleted?
if its not the same as the one shown in the file you pasted, then you had 2 on_command_errors
...but then, this traceback shows 2 from the same handler
thats weird
agh its all conflicting
your previous screenshots would suggest two on_command_errors could have raised the same error, but the tracebacks would suggest your bot processed the same message twice
just to make sure, did you ctrl+f the phrase "process_commands"?
no
oh and what happens if you use a command like normal
i did on_command_errors
does the bot respond twice or just once
ok that would definitely suggest the command was invoked twice
i dont understand how
any use of the word invoke in your code?
No
usually the library itself should never be processing a message twice, leaving the other cause to your code
should i remove and install visual studio code again?
to rule out nextcord, what happens if you create another script with commands.Bot and just one command? e.g. py bot = commands.Bot(...) @bot.command() async def test(ctx): await ctx.send('hello world!') bot.run(...)
perhaps try changing the command_prefix as well, first with the same prefix and then something different
actually just seeing the bot respond to !test with a "command not found" for same prefix would mean there's a second instance of your bot
does anyone know why this shit blocks every command
without changing your prefix, does !test happen to do anything or nothing?
ill try
no
no error
so,
- no second instance, and
- working test script, and
- nextcord not broken
then its likely an issue with your first bot
not w the cogs right?
it might be
ill check on the bot thank you!
do you happen to have the source code hosted on github?
No
by command, are you referring to @client.command()? if so, your on_message event needs to process commands in order for them to work
https://discordpy.readthedocs.io/en/stable/faq.html#why-does-on-message-make-my-commands-stop-working
like this?
oh you do have a process_commands in your on_message listener
i did on_message as an event
like in cogs its @commands.Cog.listener()
outside the if-statement, because the line should run for every message sent
await self.bot.process_commands(msg)
@commands.Cog.listener()
async def on_message(self, msg):
Channel = self.bot.get_channel(996119147337494538)
if msg.author.bot:
return
embed = nextcord.Embed(title=f"New feedback!", description=f"__**User:**__ \n {msg.author.mention} \n \n __**Feedback:**__ \n{msg.content}", timestamp=datetime.now() , color=0x4e80cf)
embed.set_thumbnail(url=msg.author.display_avatar.url)
embed.set_footer(text=f"Requested by {msg.author} | {msg.author.guild.name}")
await self.bot.process_commands(msg)
if msg.channel is not Channel:
return
moji=await Channel.send(embed=embed)
await moji.add_reaction(':Fishy:')```
omg it works i love you so much sadnkasjndkasjdaskd
Hi guys, does bot.fetch_user() has problems with some ids?
i dont see any @bot.event in your first link so i would assume you havent overridden it, meaning commands.Bot will call process_commands by itself
yes oops
like
i did, idk why i said bot.event
all valid ids should work as long as they share a guild with the bot
@commands.Cog.listener()
so do i remove it
mhm
iirc you dont even have to share a guild, any user ID can be fetched
ah yes, user's aint connected to guilds so that makes sense
🚶i almost never tried fetching a user
why do I keep getting restricted by cloud flare when my bot is sending messages to channels?
too many requests?
too many requests from the same replit datacenter, its a common occurrence for bots hosting there
ive heard you can write kill 1 in the shell as a temporary workaround, but replit's not exactly a good host for discord bots
can I handle events synchronously?
now its not
perhaps thats when there were less bots being hosted there, but now everyone's trying to get free hosting
i thought they already did with their hacker plan, whatever it was
sync vs async depends on the libraries you're using
I'm using discord.py and pyqt, having issues because the discord lib is async
i believe you'd want to look into asyncio's bridge functions (wrong term?) for interoperability then
Why it says local variable defined in enclosing scope on line xx referenced before assignment
I declared a variable outside the async def and try to use it inside an async def
More specifically, an int variable = 0 and I try to make it + 10 everytime the bot.command is run
https://docs.python.org/3/library/asyncio-api-index.html
e.g. asyncio.run_coroutine_threadsafe(), and also stuff like queues that are compatible with threading
I tried asyncio already, but I'm getting these errors
ValueError: a coroutine was expected, got <async_generator object Messageable.history at 0x7f33981df6c0>```
the code's just py print(asyncio.run(channel.history(limit=50)))
asyncio.run isnt what you'd use for that
that has to create an entirely new event loop to run coroutines
sure, but that's still a weird error in that case
eh it makes sense
anyway you'd want a thread running the event loop for discord.py, separated from your main thread
yeah but I'd have it on another thread again, would I not?
and then use asyncio.run_coroutine_threadsafe(coro, loop) in your pyqt thread to execute async coroutines
the history() generator is a bit more complex though, you'd have to make a new async function just to flatten it into a list of messages
TypeError: A coroutine object is required```
history returns an async_iterator not a coro
e.g. ```py
async def flatten(gen):
return [x async for x in gen]
in your pyqt thread:
future = asyncio.run_coroutine_threadsafe(
flatten(channel.history(...)),
loop
)
messages = future.result()```
and I can use a callback instead of blocking, right?
pyqt has their own threading stuff i believe
why does discord.py even use coroutines
the whole library is designed with async/await
anyways future.result() seems to block indefinitely
anyone got a good free host for discord bots replit stinks (used to be gud)
asyncio's a way to do concurrency in just one thread, quite performant for I/O-bound work
if you can run your stuff in another thread, you can just block normally and you wont have to get into callback hell
https://realpython.com/python-pyqt-qthread/
I'm really confused why this couldn't all run on a single thread
How can I get how long until a member is unmuted
What I mean unmuted is the member has been timeout
asyncio's event loop requires an entire thread, and so does pyqt in order to run its event loop
!d discord.Member.timed_out_until
An aware datetime object that specifies the date and time in UTC that the member’s time out will expire. This will be set to None if the user is not timed out.
New in version 2.0.
Ty
https://github.com/CabbageDevelopment/qasync
I found this, but it doesn't seem maintained
It says member object has no attribute time_out_until…
timed_out_until
Dam
Also another question, what if I just want to know how many seconds left until unmute
If I timeout 10 secs, after 5 secs there’s 5 secs left before unmute, and I want to let the bot know it’s 5 seconds left
Let me search
Quick question, say I want to dm a user they’ve been muted, what if I wanted to delete that message after a certain amount of time, how would I go about that?
!d discord.Messageable.send
!d discord.Member.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
If you'll notice there's a delete_after kwargs
if the mute is for a long period of time, you might have to store the channel+message id and timestamp in a database
ty
channel id of the user’s dms i assume??
yea, then you can use Client.get_partial_messageable() + PartialMessageable.get_partial_message() + PartialMessage.delete() to remove it
wtf is partial messageable never seen that before
its new in dpy 2.0
PartialMessage[able]s are just there if you want to make particular API requests (send/edit/delete) without having to fetch the actual channel/message objects
i barely use this module n whenever i do there’s always new shit added
makes things easier lol ig like making an api request itself
you can just use bot.http.delete_message(/s)
can someone please help me? it's giving error in dotenv, I think I uninstalled it by accident
the bot is not initializing
plsss
how can I # the channel?
@discord.ui.button(label='Open Ticket', style=discord.ButtonStyle.green)
async def count(self, interaction: discord.Interaction, button: discord.ui.Button):
with open('tickets.txt', 'r') as f:
words = f.read()
test = words.split()
if str(interaction.user.id) in test:
await interaction.response.send_message(f"{interaction.user.mention} you already have a ticket open. #ticket-{interaction.user.id}", ephemeral=True)
else:
this is my code
can someone help me? why does it say 'User' object has no attribute 'edit'
I'm trying to make a leaderboard command for my bot. I was hoping someone could assist me with this.
channel.mention
accidentally sent a other command too mb
To mention the channel? You need to somehow get the channel object and use TextChannel.mention
<#channel_id>
should work
yea but I need to get the channel id or the channel
and this is when they click open ticket
f"<#{interaction.channel.id}>"
I don't know NextCord but the error should tell you everything you need to know
Try searching through their docs, you'll probably find what you're after there
how do I get the channel id....
^^^
that will return the support channel
You want it to return their ticket?
You need to store who owns each ticket somewhere
Store the ticket channel ID in your database whenever someone makes a new ticket then
^
Store their user id aswell in the same record
And make it remove the record once the ticket is closed
i have the user id stored
In your database?
everytime a user makes a ticket there id gets stored
if its in there they cant make another
in a text file?
with open('tickets.txt', 'r') as f:
words = f.read()
test = words.split()
if str(interaction.user.id) in test:
you would have to store the channel along with the userID
Then store the ticket ID with the user ID so they are associated with one another
wait what
^ (Delliott only takes Ws)
can you help me on this
Basically right now your just storing their user id when they make a ticket
but that user ID isn't associated with any channel or anything
So you can't grab the ticket
channelid = await c.send(f"{interaction.user.mention} Please wait for staff. ({client.ticket}), to close this ticket do .close. Your next ticket can be open in 5m.")
int(channelid)
would this work?
to get the channel id
no?
idealy you'd use a database, but the next step for you that would be adequate would probably be learning about dictionaries and storing json
if a user opens a ticket,
Search for the user's ID in the db then return the corresponding ticket channel ID (if it exists)
if it doesn't exist then it means the user has no active ticket so they are allowed to open a new one
Otherwise they have a ticket open and you know the ID of the ticket channel so you can fetch_channel and mention it in your message
def save_warn(ctx, member: discord.Member):
with open('warns.json', 'r') as f:
warns = json.load(f)
warns[str(member.id)] += 1
with open('warns.json', 'w') as f:
json.dump(warns, f)
def remove_warn(ctx, member: discord.Member, amount: int):
with open('warns.json', 'r') as f:
warns = json.load(f)
warns[str(member.id)] -= amount
with open('warns.json', 'w') as f:
json.dump(warns, f)
could I use this warn code?
do you understand what dictionaries are and how to use them?
also yes databases are better for this just as Olie mentioned
I tried to use a .json like 2 years ago when I was new to dpy to store prefixes and stuff
databases are way better, I was noob back then
they're currently storing stuff in text files though so must be brand new
Aren't we all still?
I am slightly less of a noob now I think but yes true :)
not rlly
.
If I want to make a function that timeout user for 10 secs every time the command is-used, how can I make the timeout accumulable?
No just robin
meanie i cry
You mean add 10 seconds extra to a user's timeout if they're already in timeout?
Yes
That seems like a weird way to handle a timeout command.
But Member.timeout accepts datetime.datetime as the date/time at which the user will be un-timed-out. So you can probably store that somewhere and use it to figure out how much longer to keep a user timed out for, if they receive another time-out whilst already being timed out. But I don't know exactly how you'd go about doing it.
could you help me
And datetime.timedelta :3
It's actually better to use timedelta rather than datetime objects considering time zones.
True true
Again I've never really used timeout so I don't know the best way to go about doing this sort of stuff
I've made a command if you're interested.
It's fine :) someday I'll stop procrastinating and learn everything properly, but thanks lol
if you wanna show me then sure
i get no errors, but the the command doesnt work
I don't think you can overengineer it much more lol
I have the tall task of trying to build a multi-player poker game in my bot. Might ditch the multi-player aspect and just do player-vs-dealer.
bro I want to make a game in my bot
pls help me 😭
Interesting, tough with poker night it's a tough beat.
how do you update an embed
embedname.edit(embed=newembed)
Just edit the message.
No.
Unless you name the message that way I guess.
then how do you edit the message
You send a new embed.
message.edit?
npe didnt work
Yes.
Evaluating the different cards and searching for pairs, full houses, etc is gonna be the main complication for me 😭 I have a vague idea of how to implement everything but hopefully once I get it all done I can start looking at releasing the first official version of the bot :-).
Well... to be honest they are just values and combo's.
with open('file.txt', 'r') as f:
read = keyy_codes.read()
read = read.split()
if str(ctx.author.id) in read:
try to do this
ok thanks illl lyk
alr
If you'd represent card to values 1 to 14
I can get confusing quickly though
If 2 players both get 1 pair you then gotta look at the value of the pairs
Then if they both get a pair of 9s you have to go to the highest suit
Idk lot's of tiny details to account for, then again that's coding for you
Maybe I'm just small-brain when it comes to python
whats the best way to make a game in py? like a chicken fight game
how can I make ppl join and fight?
I mean I'd make a deck, then deal out "cards" then they'd have card for starters then reveal card and looking for combo's.
That's exactly the type of system I am already using in other games such as Blackjack. I can re-use parts of that code.
Though blackjack is much simpler since suits don't play any role.
Is it possible to add buttons to webhooks?
Anyway I gotta go cook cya guys round
welp
this would be easier to explain if i had the code
but i don't have a variable called "message"
just ctx and embed
Show what you got so far.
can I DM you
I'd rather not or is private code?
not really private
i'll just show you here it's a US/canada capital game bot
state = curstates[i]
embed=discord.Embed(title=f"Round #{i+1}: What is the capital of `{state}`:",\
description="Type `$guess` or `$g` before the capital to make a guess", color=0x4278f5)
await ctx.send(embed=embed)
#=await ctx.send(f"Round #{i+1}: What is the capital of {state} (Type `$guess` or `$g` to make a guess): ")
user_guess = (await bot.wait_for('message', check=check)).content
#Check to see whether user uses $guess or $g, or if the command is used at all in the first place
while not user_guess.startswith('$g'):
user_guess = (await bot.wait_for('message', check=check)).content
if user_guess.startswith('$guess'):
user_guess = (user_guess.removeprefix("$guess")).strip()
else:
user_guess = (user_guess.removeprefix("$g")).strip()
#THE MAIN THING ↓↓↓↓↓↓↓
if state in territories:
cur_dict = territory_dict
else:
cur_dict = main_dict
if user_guess.capitalize() == cur_dict[state].capitalize():
embed=discord.Embed(title=f"Good job {ctx.author}! You are correct! :)",\
description=f"State: `{state}`\nThe correct answer was: `{cur_dict[state]}`", color=0x0ca307)
await ctx.send(embed=embed)
#=await ctx.send("Good job! You are correct! :)")
else:
embed=discord.Embed(title=f"You're wrong {ctx.author} :(",\
description=f"State: `{state}`\nThe correct answer was: `{cur_dict[state]}`", color=0xe34d2b)
await ctx.send(embed=embed)
see how there are 2 embeds?
i want to edit the first embed to have the 2nd embeds content
await ctx.send(embed=embed) return a message object
So msg = await ctx.send(embed=embed) is a valid syntax.
oh nice
that didn't work
instead of editing the embed
it just sends this
🥶 long time no see this channel
<Message id=(not sharing with this server) channel=<TextChannel id=(not sharing with this server) name='bot-testing' position=2 nsfw=False news=False category_id=(not sharing with this server)> type=<MessageType.default: 0> author=<Member id=(not sharing with this server) name='(not sharing with this server)' discriminator='(not sharing with this server)' bot=True nick=None guild=<Guild id=(not sharing with this server) name='(not sharing with this server)' shard_id=0 chunked=True member_count=6>> flags=<MessageFlags value=0>>
looks like you're using jishaku
what's that
nvm
i just wanted help editing an embed
after following his part, iirc you've to use msg.edit
!d discord.Message.edit
await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
🥶 yes
that's what i did
eh, mind elaborating it a bit?
hm, i believe that it shuold work fine
may i have a look at ur code?
"that's because its running it all in the single /create command... the 2 slash commands aren't directly connected by anything...
I suggest using nextcord tasks for this instead..." someone told me that
basically
embed=discord.Embed(title=f"Round #{i+1}: What is the capital of `{state}`:",description="Type `$guess` or `$g` before the capital to make a guess", color=0x4278f5)
bot_response = await ctx.send(embed=embed)
embed=discord.Embed(title=f"Good job {ctx.author}! You are correct! :)",\
description=f"State: `{state}`\nThe correct answer was: `{cur_dict[state]}`", color=0x0ca307)
bot_response.edit(embed=embed)
await ctx.send(bot_response)
that didn't work at all
it's an async function
so
await bot_response.edit(embed=embed)
o h
try it & lemme know if u still face issue 🥶
ok
what are u exactly trying to make?
would be nice if u tell me the same thing that u told that 'someone'
ok so i made a giveaway slash command,
i did create giveaway reroll giveaway and end giveaway
But the end giveaway is not ending the giveaway bc create giveaway and end giveaway are not connected
gg bro
:>
hm, see u can make it this way
how about u create a giveaway, & the giveaway will have an ID. and in order to end any giveaway one has to pass that ID, given that it has to be used by someone who has perms & is in the same server
🥶 lmk if u find it hard to understand or if u ain't getting my point
thats actually a good idea
yes
how do i make an id to a giveaway that wasnt created yet
🥶 ok that's fked up
well, just have 2 attribtues in the table
does is have documents?
one will have the message ID of the giveaway message & 2nd will be the giveaway ID
so u can store or change or add giveaway ID & stuff on your own
thank u sm!
haha no ig 🥶
:>
Does anyone know if theres a way to access all questions, or answers in one var for the model form?
im doing one form that will display questions depending on a global var value, but after i display them i set it back to none so it dosnt show the wrong questions to someone else
but since i set it back to none i wont know what questions there are
i do use a format just Question(number)
but there will be a diff amount of questions for diff values
Im not too sure, 3-6 depending on what departmet
hm
havnt filled everything in yet but thats what i mean
i cant just check if self.question{number}.value all the way up to 6 because question{number} will litterly be none if it isnt a question so
thats not how you use classes
i mean like, thats litteraly in the docs for the example model lol
where's FormQuestions defined?
and thats how ive used forms ever since they came out and there isnt any problem
its a global var, since i cant pass a var in as i cant access self
not the best way i would like to do it
but its the only way i could think of
Hi guys !
I just coded this command that will create a Quiz. The quiz has two main functions one for asking the questionnaire and one for cancelling the questionnaire if someone writes 'cancel'.
Although this is the output I'm getting when testing it (Question 1 has been validated by question 2 before the quizz gets stopped by the cancel. I'd want it to cancel instantly):
https://paste.pythondiscord.com/pibomexeqi
EDIT: Also Question 1 shouldn't have trigger question 2 when I wrote 'cancel' :o
you're aware that you can use the init right?
theres one more way i think but its alot more work
yeah but i wont be able to access it where your supposed to have model questions
Hey, I'm making a Voice XP System and don't know what is more efficient. Should I create a asyncio.sleep() for every user joining a VC? Or save the Datetime of the Join in a DB and go through it with a for loop?
the latter
you can actually just save the timestamps instead of complete datetimes
Ok I fixed it, my filter method was returning self.ctx.message.content.lower() != 'cancel' which makes absolutely no sense !
nah, what if they chill in VC more than 24 hours or the time goes past 0
what? timestamp instead related to hours
i just re-read this, and this would work out
My problem now then would be, each department has diff amount of questions, some could have 2 others 6, so i woul dneed a way to still make the amount of questions that i need
Unless i can make 6 questions, then remove the ones i dont need inside the innit but i dont think that will work ?
unless setting it none would work
oh lol nvm.. yh ur right
@slate swan, could I setup an error handler to try and catch the errors manually?
I'm still having the issues where I don't get any errors
Every time I run the command $bread, I get the error "discord.ext.commands.errors.CommandNotFound: Command "bread" is not found"
My code:
import discord
from discord.ext.commands import Bot
from discord import Intents
intents = Intents.all()
client = Bot(intents=discord.Intents.all(), command_prefix='$')
@client.event
async def on_ready():
print(f'Bot connected as {client.user}')
@client.command
async def on_message(message):
if message.content == 'bread':
await message.channel.send('BREAD FOR LIFE BREAD FOR LOVE :bread:')
client.run("token")
@client.command()
async def bread(ctx):
await ctx.send('BREAD FOR LIFE BREAD FOR LOVE :bread:')
You were mixing an on_message event with a command
i dont use non slash cmds but im pretty pos bc your using a event not a command lol
This is not a command. For commands you would use the following:
@client.command()
async def bread(ctx):
await ctx.send('BREAD FOR LIFE BREAD FOR LOVE :bread:')```
And just remove the `on_message event`
ofcourse you can, do you have some error handler setup already?
ty ❤️
I forgot the parenthesis after the decorator, don't forget those
Whats does CTX stand for?
And I had ctx.channel lol just go with beros
ctx stands for context, which is basically just the context of the command being used. For example, who used it, where it was used
I don't, which is why I'm confused
Lmaoo
well then go for a quick lookup, search for on_error, on_app_command_error functions in your code
im high yeah
you can dynamically add new text inputs in init as i implied, but modals are limited to 1-5 text inputs and discord unfortunately doesnt allow followup modals, so you would need a way for them to answer multiple modals (perhaps, a message with buttons to open each modal?)
why content.startswith() doesn't work? if i delete it the bot will respond to any message sent but i want to make a special command for it
the only error handler I have is on_command_error which shouldn't catch it
don't use events for commands. use actual commands
Do you have message_content intent on?
Scroll up and look at WhineyMonkey's question
hmm, maybe it would be better just to do message questions then, old fassion lol, then people can send imgs too
And also this ^
i have client = discord.Client(intents=discord.Intents.default())
yeah, could you just paste all your code and send it
you can use a private github repository or a gist if number of files is the issue
ill look it up rn
@slate swan can you see if I link a private repo?
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
• The message was sent by the client
• The message was sent in direct messages
• The message mentions the client
This applies to the following events...
Intents.default have all intents but privileged ones
@waxen cradle
@client.command()
async def hello(ctx):
await ctx.send("Hello!!")
```This is an example of a command
yeah, you'll have to invite me in the repo tho
I see. I think I'll try to setup another bot on another computer and try to reproduce it first
Ty very much
When I use that format for another command it says it's not found.
Sorry!!! send error @rustic edge
show ur code
plus, wdym add them dynamically? with the exampley ou showed isnt htat just setting the label value to something, not adding more questions
discord.ext.commands.errors.CommandNotFound: Command "cat" is not found
import discord
from discord.ext.commands import Bot
from discord import Intents
intents = Intents.all()
client = Bot(intents=discord.Intents.all(), command_prefix='!')
@client.event
async def on_ready():
print(f'Bot connected as {client.user}')
@client.command()
async def bread(ctx):
await ctx.send('BREAD FOR LIFE BREAD FOR LOVE :bread:')
async def cat(ctx):
from IPython.display import Image
import requests, json
catURL = 'http://aws.random.cat/meow'
imageURL = json.loads(requests.get(catURL).content)["file"]
img = Image(requests.get(imageURL).content)
await ctx.send(img)
client.run("token")```
You need a new decorator
Why are you importing stuff in ur command?
^^
dont use requests library!!!
!blocking
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
from IPython.display import Image
import requests, json
@client.command()
async def bread(ctx):
await ctx.send('BREAD FOR LIFE BREAD FOR LOVE :bread:')
@client.command()
async def cat(ctx):
catURL = 'http://aws.random.cat/meow'
imageURL = json.loads(requests.get(catURL).content)["file"]
img = Image(requests.get(imageURL).content)
await ctx.send(img)
import discord
from discord.ext.commands import Bot
from discord import Intents
from IPython.display import Image
import requests, json
intents = Intents.all()
client = Bot(intents=discord.Intents.all(), command_prefix='!')
@client.event
async def on_ready():
print(f'Bot connected as {client.user}')
@client.command()
async def bread(ctx):
await ctx.send('BREAD FOR LIFE BREAD FOR LOVE :bread:')
@client.command()
async def cat(ctx):
catURL = 'http://aws.random.cat/meow'
imageURL = json.loads(requests.get(catURL).content)["file"]
img = Image(requests.get(imageURL).content)
await ctx.send(img)
client.run("token")```
ty
yw
❎ ```py
imageURL = json.loads(requests.get(catURL).content)["file"]
✅ ```py
imageURL = requests.get(carURL).json()["file"]
its done the same as regular Views by calling self.add_item() and passing your TextInput instance
oh so i can litterly just define all my questions inside init with self.add_item?
i think your questionnaire can be done just with buttons/modals/app commands (for the attachment part), but it would be much more complicated than a message-based implementation
async def main(ctx):
while True:
if console.alive:
frametime = time.time()
bot.run(frametime)
scheduler.run(frametime)
console.run()
await client.send()
await asyncio.sleep(0.5)
else:
await client.close()
print("QUIT NOW.")
os._exit(0)
client.c.loop.create_task(main())
client.run()
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook i dont understand what should i do exactly
yeah im gonna stick to forms since it would take me years to do messages for 30 diff departments
and just make people use imgur or something
https://femboi.best/FVNP7D5L u mean something like this right?
or did i missunderstnad you
because if i can do it like that, my life is so easy
pretty much
is varthing a classvar?
i woul dlove to cry rn
wish i knew that 2 months ago, the amount of pain and suffering ive done with forms to do dymanic questions with jaggy ways
😭
but thank you
then i guess i can just access my self.varthing or what ever again in the code to check what set of questions its using
it sbeing passed into the model
its nothing rn i just was sharing a example
passed into the model as in inside the init right?you can access it from there directly
Who needs help?
im not needs help
i do
yea i know
@dense coral
i just didnt know i could use self.add_item or what ever inside innit to define questions
just a second
alr
why you are use on this ? await asyncio.sleep(0.5)
but, I think that this is not the problem
it isnt
Guys, if i want my bot to send a message everyday at a specific hour only how can i approach this (i tried with the good old While True and time.sleep() and asyncio.sleep, but they dont work)
async def watching():
await bot.wait_until_ready()
client.loop.create_task(watching())```
This is the template for the loop
is anyone able to help with this
look at what yarin sent, i tried with While True like u did and for me at least it doesn't work
both methods are bad you'll have to use a task loop ```py
from discord.ext import tasks
@tasks.loop(<time here>)
async def send_message():
# do your stuff to repeat after time
@send_message.before_loop
async def before():
await bot.wait_until_ready()
send_message.start()
much appreciated 🙏
Which one's better for efficiency?
timer = threading.Timer(30, do_something)`
timer.start()```
or
```py
asyncio.sleep(30)
2nd
how do I make an app command error handler
on_app_command_error event
waittt i think there's one more thing that can cause your no error issue, do you use bot.run() or bot.start() ? @abstract kindle
async with bot:
await load_extensions()
await bot.start(data["token"])
then ```py
ayncio.run(main())
yeah thats the issue, you'll have to manually configure logging if you use bot.start, can you just try replacing it with bot.run() for a while and try?
bot.run is not a coroutine, right
yea you wont be awaiting it
[2022-11-08 14:17:17] [INFO ] discord.client: logging in using static token
yeah great, it didnt use to print earlier right?
I think it fixed the logging? But how come it says logging in with a static token? Also none of my commands are being found
did you remove the load_extensions() ?
static token means a bot token, thats totally normal
discord.py added these logging in 2.0
None of the commands are being found anymore. Also, how come I would remove load_extensions()? That loads all my cogs
can i see your updated bot running code
Hold on, I have everything in my main file in a main() function so I could use await, is that fine?
ofcourse
I think I did that so I could start tasks in the on_ready() event
I had a setup_hook, but that was so I could setup bot.db for my database
bot.run(data["token"])
asyncio.run(main())
This is the part that runs though
just move the bot.run() inside your main function bud
your bot.run() is blocking asyncio.run() here, so no extensions are getting loaded
but not under
await with bot:
async with bot:
await load_extensions()
bot.run(data["token"])
``` inside the main function
okay that's what I had, one sec
yeah i got this error
RuntimeError: asyncio.run() cannot be called from a running event loop
sys:1: RuntimeWarning: coroutine 'Client.run.<locals>.runner' was never awaited
hm can you send all the runner code
!d discord.utils.setup_logging
discord.utils.setup_logging(*, handler=..., formatter=..., level=..., root=True)```
A helper function to setup logging.
This is superficially similar to [`logging.basicConfig()`](https://docs.python.org/3/library/logging.html#logging.basicConfig "(in Python v3.11)") but uses different defaults and a colour formatter if the stream can display colour.
This is used by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") to set up logging if `log_handler` is not `None`.
New in version 2.0.
@bot.event
async def on_ready():
print("Bot is ready.")
activity = discord.Game("-help")
await bot.change_presence(status=discord.Status.online, activity=activity)
print(f"-- BOT RAN --\nRan at: {now}")
drop_task.start()
farm_task.start()
I do have this IN the main function
that should create an issue
Got it. Move it outside the main?
oops, * not create an issue
async def main():
async def load_extensions(): # Function for loading cogs upon bot.run
for filename in os.listdir('./Cogs'):
if filename.endswith('.py'):
await bot.load_extension(f'Cogs.{filename[:-3]}')
async with bot:
await load_extensions()
bot.run(data["token"])
``` This is entire main function now
actually you know you can fix it even more easily
just revert the code to how it was
and add discord.utils.setup_logging() just before bot.start
it will fix your issue
it took a whole day lol
Yeah I was so lost
no probss, the soln was easier than all we tried lol
I was just putting print statements and debugging ALL over the place and it was getting old
for real
[2022-11-08 14:34:07] [INFO ] discord.client: logging in using static token
[2022-11-08 14:34:09] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 261225937d7fda3da5ff7552e1262164).
```So this is normal?
It scares me cause red = bad
yes thats totally normal
INFO logs are just about the actions your lib is doing
you just gotta check warning logs if any of them get raised
Got it
Also, I'm kinda new to slash commands. What's the best practice for syncing commands?
i use stuff similar to setup_hook for automatic syncing
people will also suggest to use a command to do the syncing
so the code doesnt sync itself all the time
can i use database in cogs?
yeah, previously I made a reload command to reload whatever Cog I chose, and I had an option to sync commands
you can do that anywhere!
oh thats great
thankss
its totally fine if that works for you
cool. also, I run my bot in 2 different servers. Would I have to have 2 different sync lines?
idk about syncing stuff in discord.py, you can wait for someone else to respond maybe
( if its a global command you wont have to sync seperately lol )
I think I figured it out. Bot has to have proper permissions in both guilds lol
yea the applicationcommands scope
does the decorator also work? as in
@app_commands.guilds(856915776345866240, 977351545966432306)
@discord.app_commands.guilds(*guild_ids)```
Associates the given guilds with the command.
When the command instance is added to a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree"), the guilds that are specified by this decorator become the default guilds that it’s added to rather than being a global command.
Note
Due to an implementation quirk and Python limitation, if this is used in conjunction with the [`CommandTree.command()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.command "discord.app_commands.CommandTree.command") or [`CommandTree.context_menu()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.context_menu "discord.app_commands.CommandTree.context_menu") decorator then this must go below that decorator.
Example...
yea
nextcord.errors.ApplicationInvokeError: Command raised an exception: OperationalError: no such column: command
perfect. Thanks again for your help sarth, saved me a lot of frustration
!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.
https://paste.pythondiscord.com/igoqufucom
trying to make a database thats its taking the member who did the giveaway and then he can end it w the id he did
you should use a setup_hook instead of doing stuff in on_ready first of all
Oh thanks
you can put that db stuff in your bot file btw
add a db connection as a botvar
why doenst content.startwith(!) work inside the command?
on_message is an event, not a command => wrong decorator
also, time.sleep is blocking, you should use await asyncio.sleep(...) from the asyncio lib
oh yea thx, even imported it but forgot
but what decorator could i use?
in the quickstart of the docs, it even shows an example of on_message....
How can I make the @tasks.loop(minutes=2) start after 2 Minutes and not run once and repeat every 2 mins? So the first run starts after 2 mins
use @task.before_loop then cancel the task
what are the limitations with background tasks in discord?
what exactly do u mean by that
💀 you mean @task.before_loop?
uhhh yea sumn like that lmao
i want to creat a mongodb streamer which will send a user a message in the background when some values change
originally i was going to make this run seperate to the bot but i dont think i can send private messages without running it in in discord.py/ nextcord?
ok tyty
Also are normal commands (not slash) now deactivated completely for public bots?
Nope, unverified bots still get content intent without filling out the application
is there a way can send direct messages without using discord.py thought the bot?
yeah use the rest api
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
i need the users channel id for this tho? not just the user id?
you send the message to their dm channel, not the user object
their user-id is the channel-id there
https://discord.com/api/v9/channels/user-id/messages returns me a 401 error, when using the bots authorization code
show ur code lol
im just using postman atm for that, not wrote anything up
when browsing through the requests ive sent when sending a message the channel-id isnt the same as user-id for private messages?
alright
okay so you gotta create a dm channel and get it's ID first then you can send a message there
also while using postman, did you provide the headers?
yeah copied the bash from discord request
so ive just tried that changing the auth token and recipients and 401 error again -.-
401 means lack of authorization
using the bots token
did your headers look like this ```py
{"Authorization": "Bot <your token here>",
"Content-Type" : "application/json"}
ive got these enabled with the correct token, still coming back 401. ill try without postman see if thats the issue
?
You're sure this is where the error is? I don't see await channel.send('hello') in that image
i changed the hello to "somebody redeemed a bronze key"
And is it still the same error?
oh wait nvm the bot was running LMAO
how would i wait for a specific users, user input
like if i were to do $input
and someone else says something for some reason it takes that instead
how do i make my discord bot leave the guild
!d discord.Guild.leave
await leave()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Leaves the guild.
Note
You cannot leave the guild that you own, you must delete it instead via [`delete()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.delete "discord.Guild.delete").
the last guild it was added to to be specific
You can always have a global var of the last guild it joined to or you can get the object
no actual way of doing that other that getting the guild id itself then getting the obj like noid said.
i ahve @client.even on_guild join can i possible check if len(client.guilds)>1: await.leave()
if ur using on_guild_join just do guild.leave() and it will leave the second it joins a guild
ok but
thats only if its len(client.guilds)>1
maybe i want len(client.guilds)> some N
u would just be leaving random guilds at that point
no. all that would do is leave the last guild u appended
u cant get the last guild ur bot joined other than getting the guilds id and getting the guild obj
Because its a method and isnt in scope
wdym?
how doi make it work
You use the method on a guild object?
Guild.id returns a snowflake and gets treated as an int, no? So using int.leave which isnt a method the object has if not defined, isnt correct.
what should i be doing?
^
yes

[2022-11-08 19:14:19] [ERROR ] discord.ui.view: Ignoring exception in view <Commissions_Question01_Department timeout=None children=1> for item <Select placeholder='Select a department.' min_values=1 max_values=1 options=[<SelectOption label='Development' value='COM_DEP_1' description='MC Plugins, Discord Bots, Web Development' emoji=<PartialEmoji animated=False name='⚙️' id=None> default=False>, <SelectOption label='Minecraft Building' value='COM_DEP_2' description='Builder' emoji=<PartialEmoji animated=False name='🏦' id=None> default=False>, <SelectOption label='Design' value='COM_DEP_3' description='GFX, Web Design, Illustration, Vector Artist, 3D Artist, MC Texture Pack Designer' emoji=<PartialEmoji animated=False name='🎨' id=None> default=False>, <SelectOption label='Writing' value='COM_DEP_4' description='Writer' emoji=<PartialEmoji animated=False name='📃' id=None> default=False>, <SelectOption label='Video & Audio' value='COM_DEP_5' description='Voiceover, Video Editor, Trailers' emoji=<PartialEmoji animated=False name='🎙️' id=None> default=False>, <SelectOption label='Setups' value='COM_DEP_6' description='Setup Specialist, Server Administrator, Discord Setup Specialist' emoji=<PartialEmoji animated=False name='🪚' id=None> default=False>, <SelectOption label='Close' value='COM_DEP_CLOSE' description='Close your ticket.' emoji=<PartialEmoji animated=False name='❌' id=None> default=False>] disabled=False>
Traceback (most recent call last):
File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "C:\Users\kaelm\PycharmProjects\Main-bot-recreation\cogs\ticket\master.py", line 210, in select
if option.value == "COM_DEP_1":
AttributeError: 'Select' object has no attribute 'value'```
https://i.leaked-your.info/dhZV99Nj
what is it again
i forget
i thought it was values[0] but that dosnt work so
it's values not value
pycharm is being homosexual then, said value was right but not values lul
thanks
one more question
is there something to mark a interaction as responded too?
so it dosnt say interaction failed
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
quick question again abou tthat, since im not setting it to a var how do i access the value of what was answered?
just realised that haha
sorry
you use the value attribute of the text input
wdym?
!d discord.ui.TextInput.value
property value```
The value of the text input.
i.e. py class MyModal(discord.ui.Modal): my_input = discord.ui.TextInput(...) async def on_submit(self, interaction): answer = self.my_input.value
yeah but its not being set to a var
you have to store the text input somewhere
put it in a list or a dictionary or something
mm
wdym by this?
its inside my innit so
how would putting them in a list or dict do anything
or
so you're able to get the answers to each input
how do i store them tho? since im using self.additem
questionone = self.add_item()
?
construct the text inputs beforehand, then use add_item() afterwards
e.g. ```py
self.inputs = [
discord.ui.TextInput(...),
...
]
for text_input in self.inputs:
self.add_item(text_input)
and in on_submit():
answers: list[str] = [text_input.value for text_input in self.inputs]```
self.inputs = [
discord.ui.TextInput(...),
...
]
for text_input in self.inputs:
self.add_item(text_input)
inside my innit still?
yes
oo oke! thanks
then to access it, answers[0].value im guessing?..
er no, the answers was showing how you'd turn that list of text inputs into a list of strings
if you dont care about that you can write self.inputs[0].value
ahh oke
is there any way to run a command when my bot goes offline?
hello! i'm trying to set up a bot but i can't install discord.py using pip. Anyone having the same issue?
ERROR: Failed building wheel for yarl
Failed to build multidict yarl
ERROR: Could not build wheels for multidict, yarl, which is required to install pyproject.toml-based projects
idk if it's something really simple or a huge problem, because i started coding in python and in general recently, so i still don't know a lot. i'm working on the bot as a way to learn the language
does anyone know how to fix this?
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
thank you
help me pls
Please, can someone help me? i'm trying to initialize my python bot and it's giving this error, it didn't give this error before
it's giving this error when booting
in that folder
.
How do I do this
aint no way
like where are the docs for it
you type the answer to the questions dawg
WHAT DOCS 😭
fill out the info
bruh the discord api docs to use the forms feature
dunno if you figured it out yet, but python 3.11 was released only two weeks ago so not all libraries have uploaded prebuilt wheels for it
you can either downgrade to 3.10 (the simple choice), or download the necessary build tools for pip to manually compile those wheels, which is sort of explained somewhere above your error message
those are known as modals, you'll find the related documentation in the "Message Components" and "Receiving and Responding" section of the docs
https://discord.com/developers/docs/interactions/message-components#text-inputs
Thank you, which library should I use for this?
I believe discord.py does not support this correct?
discord.py supports all forms of interactions* in the latest release, 2.0
*barring the bleeding edge stuff, in particular role/user/mentionable select menus
what do you mean by "*barring the bleeding edge stuff"
as in the particular feature i described came out very recently (about one month ago), and 2.0 came out before then
its just a sidenote, modals are supported
you can see an example of how they're used here
https://github.com/Rapptz/discord.py/blob/master/examples/modals/basic.py
and the related documentation:
https://discordpy.readthedocs.io/en/stable/interactions/api.html#modal
it seems there's something wrong with your dotenv package, perhaps related to a package conflict, though i dont understand why a package-lock.json file for npm is there
id ask about it in a help channel and also paste the output of pip list in your terminal (#❓|how-to-get-help)
who wants to make a bot with me?
aw man
i think we were discussing this a few days ago
not sure if that was you but someone sent an image of a select menu with roles and users
yup that was me
Thanks 😊 🙏
ahaha my bad, my memory is not all that great
previously select menus were not visible on mobile client does it work now?
when did that happen? i remember using them on iOS and android a while ago
about a month or two when i was testing modals showed on my pc not mobile
ah i think i remember that too, it was a weird experience
the api straight up blocks selects in modals now (i tested it a minute ago)
ic thanks for the info❤️
!d discord.ext.commands.Greedy
class discord.ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.
When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.
For example, in the following code:
```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
``` An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
wb slash commands
ok yeah it works the same for slash command
Hello, I'm looking for ways to make my own discord.py custom events
@bot.event
async def on_my_event(param1,param2,*etc):
pass
I came across this stack overflow post
https://stackoverflow.com/questions/64810905/how-do-i-emit-custom-discord-py-events
In discord.py, I am able to use even listeners like this:
@bot.event
async def on_event_name(*args, **kwargs):
# do stuff
I have seen some libraries that appear to emit custom events, ones tha...
can any one please explain how Bot.dispatch works ?
I don't see it in the docs for discord.py
!d discord.Client.dispatch
No documentation found for the requested symbol.
Oh oops
It’s Bot.dispatch("event_name", events_arg1, event_arg2, …)
The event name should not have on_
is it async ?
Nope
so apparently discord has select menus and stuff
where you can choose multiple
how would i do this? the closest is discord.ui.Select, and it doesn't exactly offer multiple select choices
What do you mean?
@torn sail
just curious
what library does discord.py use to handle event-dispatching ?,
itself
!d discord.ui.Select - Set the max_values to more than 1
class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu with a list of custom options. This is represented to the user as a dropdown menu.
New in version 2.0.
Thankss
!d discord.utils.utcnow
discord.utils.utcnow()```
A helper function to return an aware UTC datetime representing the current time.
This should be preferred to [`datetime.datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "(in Python v3.11)") since it is an aware datetime, compared to the naive datetime in the standard library.
New in version 2.0.
Hello, I'm looking to create a command to display the time dynamically based on the customer's location, normally it's possible but I don't know how to go about it 😅
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
this can help do it for you
{'cogs.modmail': ExtensionFailed("Extension 'cogs.modmail' raised an error: ModuleNotFoundError: No module named 'configuration'")}
Loaded: cogs.modmail
import discord
from discord.ext import commands
from configurations.configuration import config
from configurations.messages import res_msg
from utilities.functions import get_embed, confirmation
Why?
Yes it doesn't really help me but hey I'll try like that
if I’m not mistaking just doing using datetime.datetime.utcnow() will display the time based on their time zone.
nope, this will return the time based on the local machine, aka the current time where the bot or the program is executed
classmethod datetime.utcnow()```
Return the current UTC date and time, with [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.datetime.tzinfo "datetime.datetime.tzinfo") `None`.
This is like [`now()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.now "datetime.datetime.now"), but returns the current UTC date and time, as a naive [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") object. An aware current UTC datetime can be obtained by calling `datetime.now(timezone.utc)`. See also [`now()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.now "datetime.datetime.now").
Warning
Because naive `datetime` objects are treated by many `datetime` methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing the current time in UTC is by calling `datetime.now(timezone.utc)`.
shoulda specified, if u do it in the time stamp of an embed it’ll show correct time for that used
yeee this.
hello so I am running a discord bot and hosting it over replit with an hosting file or actually keep_alive but I am having the problem in the image down there that its giving me the wrong time. I hope someone had this before and can help me with it
this error is also causing the bot not to get online
Should I use image as the Monopoly board like myuu
This is not an error
This thing means ur uptimerobot is working :/
yes, but the time is wrong
Check ur token maybe?
I reseted and tried it

