@commands.command()
async def panel(self, ctx:commands.Context):
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
elif not getattr(ctx.author.voice,'channel',None):
await ctx.send('Join a voice channel first lol.')
return
else:
vc: wavelink.Player=ctx.voice_client
if not vc.is_playing():
await ctx.send('Play something first.')
return
embed=nextcord.Embed(title='Music Panel', description= 'Control Runa by clicking on the buttons below.')
view=ControlPanel(vc, ctx)
await ctx.send(embed=embed,view=view)
``` could someone help me fix the error please?
#discord-bots
1 messages · Page 77 of 1
wym
ControlPanel only takes 1 positional argument being self
The answer given isnt correct and can cause more confusion.
so it should be view=ControlPanel(self)
instead of view=ControlPanel(vc, ctx) ?
?
i have 2 classes in this cog and i thought that might be whats messing it up, but im not sure
class ControlPanel(nextcord.ui.View):
def __init(self,vc,ctx):
super().__init__()
self.vc=vc
self.ctx=ctx
#buttons below
class MusicCog(commands.Cog, name='Music'):
def __init__(self, bot):
self.bot = bot
you forgot the other 2 ending underscores in the method created in ControlPanel (__init)
bruh i didnt even change the code and now the bot responds after like 10 sec
blockingio
So obviously this would work as an indentation command await ctx.send('>>> Pong! %sms' %response_time)
But. My question is how would i format the text for something like the formats of
'css
askjdnasjkdn askjdnaskjdn
'
i know obviously thats not the format but wasnt sure how to put it in the code for something that is a single line like that... Sorry I am new to discord Bots and python here.
ooo thank you
code blocks?
compact messages? 😳
arent those called inline embeds?
what is that
if youre referring to them ofc
This
oh, I always called them replies 🗿
ok
@nextcord.ui.button(label='Resume/Pause', style=nextcord.ButtonStyle.blurple)
async def resume_and_pause(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
if not interaction.user==self.ctx.author:
await interaction.response.send_message('You can\'t do that. Run the command yourself to use these buttons.', ephemeral=True)
return
for child in self.children:
child.disabled=False
if self.vc.is_paused:
await self.vc.resume()
await interaction.message.edit(content='Resumed', view=self)
else:
await self.vc.pause()
await interaction.message.edit(content='Paused',
when i press the resume/pause button while a song is playing, it resumes it instead of pausing it. is there something wrong with my if statement?
nvm, i got it!!
@silk fulcrum I'm not sure that's why I'm asking
And was trying to give an example
and @primal token what do you mean by code blocks im sorry
hi got problem i have installed python 3.7 and it cant show on cmd
U using the latest version?
i just updated
so yea
whats the command to update again maybe i did it wrong
as i havnt used python in a good while
Any idea why this isnt working ?
modList = [394506589350002688, 697725862128386048] # just some ids as examples
def check_Mod(ctx):
if ctx.author.id in modList:
return ctx.author.id in modList
@commands.command()
@commands.check(check_Mod)
async def test(ctx):
await ctx.send("You are a mod!")
saying test isnt a command
You need to flip the order of the decorators I believe
It's discord.Interaction.delete_original_response() not discord.InteractionResponse.delete_original_response()
If your interaction object was interaction, you would do interaction.delete_original_response() and not interaction.response.delete_original_response()
yes?? thats what i got
see this @indigo pilot
ohh
yea that dosnt work etiehrthought i said that
lol
What error do you get when you try interaction.delete_original_response()?
let me see lul
AttributeError: 'Interaction' object has no attribute 'delete_original_response'
Is this in a cog?
!d discord.Interaction.delete_original_response
await delete_original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the original interaction response message.
This is a lower level interface to [`InteractionMessage.delete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.delete "discord.InteractionMessage.delete") in case you do not want to fetch the message and save an HTTP request.
evening all, I was wondering if any could advise what I should be looking into when I want to lock a reaction role down to the message posted, so im not picking up roles on any message I may use these selected emojis. I seen Rapportz example where it requires a message ID but is there a way to do it without a message ID? Do i need to look for the guild id, get the channel and then use that channel to fetch the payload message?
yea its in the docs thats how i found it
but it wont work
It was renamed a while ago so make sure you update
i did but again like i said i may of did it wrong
do i just pip install then
or is there a cmd
wait no i did do it right
weird
fixed it it was delete_original_message but that still dosnt work for me lol
if scope == 'all':
guild = ctx.guild
members = guild.members
print(members)
print(len(members), members)
for x in members:
print(x)
await x.add_roles(role, reason=None, atomic=True)
its only printing the bot
Hey hey... how could i make a monthly payment thing? I have 0 knowledge into this and honestly i don't even know what to start with
Look into Stripe API
stripe requires a credit card
You probably don’t have the guild members intent
How would one get it?
Well yeah. If you’re going to do anything financial with your discord bot you better have a bank account
Otherwise I’d just forget it
this will happen once i turn 18... which is next year lol
but i still need something till then
do u think paypal is a good solution?
Probably not
If a bot wanted me to make payments through PayPal i better be ready to say bye bye to the money
Not really secure for business transactions
What’s stopping me from running away with your money?
How could you even do that?
Just not provide them the service you say you will
Sorry im getting confused right now
so it's because of a low security? is that what u mean?
i didn't get the part where u said "running away with your money"
yes
What’s stopping you from not giving them that bot function
Your users can’t be certain of that
Why would i do that?
also i want to make it automatically...
no need for me to manage that
Don’t know if you can do it automatically
Your users don’t know that
Ok so lemme tell u what im currently up to do
its a NSFW monthly subscription
that way we can avoid some minors from seeing it.. im also a minor but meh
What would u use "to do it automatically" if u were me?
like what i have to do is to somehow pull the user ID then add it to a db
if the user id is there then let the user use the NSFW commands...
@sick birch Yes looked into it. to allow payments they asking for the IBAN
Patreon accepts minors?
How would i invaildate said key ?
@bot.command()
async def redeem(ctx, key):
query.execute("""SELECT CLAIMED_KEY FROM KEYS WHERE USER_ID = ?""",(ctx.author.id,))
list_keys = [row[0] for row in query.fetchall()]
if key in list_keys:
await ctx.send('vaild key ')
# Invaildate said key
else:
await ctx.send('invaild key ')
something like this ?
im using sqlite3
nvm fixed by my self ^
bruh
How would one recommend I save a string set with a command (unique to each server)
I was thinking SQL data store with firebase
Stripe
I'd create a website using discord Oauth and integrate it with Stripe
Once a user successfully does a transaction, I can add their ID (through oauth) to a database
The discord bot also has access to this database, so it can verify the premium status of users
hey i wanted to make that the bot updates the slash commands but every time this Message comes:
KeyError: '1016801750214246472' ```
That means update_guild_commands has no 1016801750214246472 in it
Maybe
!d discord.ext.commands.Context.author
Union[User, Member]: Returns the author associated with this context’s command. Shorthand for Message.author
The user’s username.
thanks
import requests
import discord, time
import random, threading
import asyncio
from discord.ext import commands
bot = commands.Bot(command_prefix=".",intents=discord.Intents.all())
@bot.command()
async def crash(ctx):
ok = await ctx.send('**Checking api , Please wait**')
game = requests.get("https://rest-bf.blox.land/games/crash").json()
def lol():
r=requests.get("https://rest-bf.blox.land/games/crash").json()["history"]
yield [r[0]["crashPoint"], [float(crashpoint["crashPoint"]) for crashpoint in r[-2:]]]
for game in lol():
games = game[1]
lastgame = game[0]
avg = sum(games)/len(games)
chance = 1
for game in games:
chance = chance = 95/game
prediction = (1/(1-(chance))+avg)/2
if float(prediction) > 2:
color = 0x81fe8f
else:
color = 0xfe8181
desc = f"""
**Crashpoint:**
{prediction:.2f}x
**Chance:**
{chance:.2f}%
"""
em=discord.Embed(title="DEMON V2",description=desc,color=10428871)
em.set_thumbnail(url="https://i.imgur.com/axLm3p6.jpeg")
await ok.edit(embed=em)
I get keeping like this error idk what wrong w/ it , somtimes it works , sometimes it doesnt
^ error log
i feel like this is an easy fix but i cant see it
!blockingio
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!
how do i make it that it works?
And it seems like it didnt return valid JSON
I don't know how code works 
?
I mean, Idk how he's going to put guild IDs in update_guild_commands
poor choice of words
I'm suck at explaining things
Yea i think its cus the website takes a long time to boot up , no idea how to fix that tbh
well more like it just takes a long time to load
how can i make this send in blocks instead of sending line by line
''' file = open("medivia.txt")
lines = specified_lines = [0, 1, 2, 6, 7, 8]
print("Sending lines")
for pos, l_num in enumerate(file):
if pos in specified_lines:
print(l_num)
await ctx.send(l_num)
await ctx.send("----------")'''
Got two things to fix...
First: TypeError: abc.send123() missing 2 required positional arguments: 'self' and 'ctx'
Second: It always creates a new channel with the same name when using the command to load the cog...
Hello, I was wondering if anyone would be able to speak to me about sending messages through the webhook via python script. I posted about it in a help channel and was referred to here. Please reply to this message if so. Thank you!
Please refer to #help-bread
I am rather new to python as well, I apologize in advance.
do asyncio.run(foo())
Am adding that to the end?
yeah thats the way to start an async func
from discord import Webhook
import aiohttp
import asyncio
async def foo():
async with aiohttp.ClientSession() as session:
webhook = Webhook.from_url('https://discord.com/api/webhooks/xxxxxxxxxxxxxxx/i5957RCj2umzw5W9QFw-ZaaUEY8YlpCGtSOoQcxZSuLnICzZGvvTjTUDHAbQa5rygECa', session=session)
await webhook.send('Hello World', username='foo')
asyncio.run(foo())
!d discord.Webhook.from_url
classmethod from_url(url, *, session, bot_token=None)```
Creates a partial [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook "discord.Webhook") from a webhook URL.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
huh
?
oh yeah then @hazy isle if your on 1.7.3 you pass the adapter kwarg instead of session
adapter being one of these https://discordpy.readthedocs.io/en/v1.7.3/api.html?highlight=webhook from_url#discord.AsyncWebhookAdapter
you're*
*your
no
yes
yr'oue*
await request(verb, url, payload=None, multipart=None, *, files=None, reason=None)
so use this?
await
request is a method of discord.Async.WebhookAdapter which I doubt you need to use, you probably just need to create an instance of discord.Async.WebhookAdapter and pass the instance to discord.Webhook.from_url with the session being passed to the newly created instance of discord.Async.WebhookAdapter
Being newer to python, much of this I am learning as we speak.
May I see an example of how this would look?
The terminology "passed" does not translate properly in my head.
Well, if i continue to explain i doubt you will get the terms or how it would work as this is basic python OOP and understanding would be a disaster if you havent studied about the paradigm or how python uses it
I would recommend learning, Basic python if you haven't, python's OOP and then asynchronous programming and its implementation in python, over causing unnecessary headaches to yourself
Okay, back to the books I go. Thanks for the attempt to help then. I appreciate it.
I have just started messing with python scripts being used with discord.
This appeared to be rather simple, but the wall I hit with this simple test of sending messages to discord really just grinded my gears. In the help channel, they said it appeared I was trying to mix to different style of it together. I think I am just trying to make it work based off of what I can read. lol
if you need help on learning the given concepts and topics check out:
Learning basic python: https://realpython.com/tutorials/basics/ , https://www.youtube.com/watch?v=YYXdXT2l-Gg&list=PL-osiE80TeTskrapNbzXhwoFUiLCjGgY7
Learning asynchronous programming and its implementation in python: https://www.youtube.com/watch?v=Xbl7XjFYsN4&list=PLhNSoGM2ik6SIkVGXWBwerucXjgP1rHmB
Learning python's OOP: https://www.youtube.com/watch?v=ZDa-Z5JzLYM
I will save these and check them out. Thank you for pointing me in the right direction!
if you need them saved e.g on a dm reply to the message with .bm, note: you need to have your dms opened
I went ahead and saved this to my personal server.
I feel like I have a decent grasp on the basics, but like the bare basics. I was able to make a script that counts cards as a little project. I will check this out in depth. Thank you.
np!
bots create they’re own role upon joining servers right?
An Integration role, yes.
Are you like brand new to python to where you haven’t learned about variables or functions and stuff like that? Or are you past that? Because if you brand brand new, I recommend checking out programmingwithmosh on YouTube, I pretty sure that’s his name
I am past that. I still use a lot of resources to refer to constantly. I would say about two months of self study and trying to implement things. I tend to do well with basic exercise now. Some of the references take me a little bit to look up. I really don't have anyone personally to lean on for questions. So like 99% of everything I do has came down to trial and error. Then it clicks.
Also, he was the first video I spent time on. Great vids.
The 1 hour video. 
Yes he has great tutorials. Respect
That’s the one I watched, did you know he has a 6 hour long video!!!
I did not and I don't think I even have the mental capability of watching it.
I've only recently started to mess with python and discord together. I think that is why this is why I am having such a difficult time with such a simple thing.
Like I am pulling this from discord.py/readthedocs.io
from discord import Webhook
import aiohttp
async def foo():
async with aiohttp.ClientSession() as session:
webhook = Webhook.from_url('url-here', session=session)
await webhook.send('Hello World', username='Foo')
Me neither, and I just started teaching myself and learning python also. I would say I’m between beginner and intermediate.
lol so that's what is more frustrating.
Closer to beginner for me
Same. We would be the blind leading the blind.
Stuff like this I don’t understand yet
So far all I’ve done is make a auto bridge thing for Minecraft (I don’t use it) and I also made a T-Rex run game cheat
I comprehend the formatting. This is my first experience with async. So that's that.
I made a script that counts cards for you in black jack. (no I don't use it, it was just to test my understanding.)
Nice
It has a fancy menu in it as well. lol
While loops took me forever and a day (maybe 2 full days) to learn.
So far I’m just using my coding skills that I have right now, and making bigger things, and maybe finding out more and more by scrolling through this discord and sometimes asking questions
Took me way longer, you're making good pace
I’m good with while true loops, that like 20% of the 2 projects I have made so far.
Idk if you guys mean more complex loops tho
Thank you. It appears that python and coding in general is a very logical process, so I tend to do well with logical problem solving.
For me though, it is extremely difficult to really spend a good amount of time in it as I have a full time job that is not related to coding at all and small family unit. lol so I really can only mess with this stuff in the evenings. Maybe get 2-4 hours in here and there.
That’s a good schedule. If keep that up for a while, you could learn a lot pretty quick.
Oh, then you're making real good pace. Keep it up!
I wouldnt say theyre good in terms of explaning in depth, hes good to use his videos as a reference or as a tree of concepts to use and study those concepts deeply with other tutorials that are strictly talking about the given concept, But i wouldn't say with one video youll actually understand everything over syntax or a simple resumed explanation.
You should get into classes if your really passionate abt coding , only a 1hr a class , would be a fun passtime if you like that typa stuff
Yes that is true. But he still gives pretty good tutorials. He gives you the simple stuff of the basics
For me , thats what really spark my coding , i took a java class and it really help me understand the fundamentals of coding
I've contemplated it. Harvard actually offers a free python class I have been playing with the idea.
Also, like this makes no sense to me, thus far. I pulled this right from discord.py
import requests
from discord import Webhook, RequestsWebhookAdapter
webhook = Webhook.partial(123456, 'abcdefg', adapter=RequestsWebhookAdapter())
webhook.send('Hello World', username='Foo')
Obviously I filled it in with the correct things on my end, but when I run it from cmd it just sits there forever. The message never goes through to the discord. lol like WHY?! 
Hes only good at explaining a concept in a compact understandable manner but i wouldnt really recommend it to absolute beginners maybe after they have learned the concepts and want to check if theyre missing something
Ok
ok
I mean I’m a beginner myself. And I used his hour long tutorial and though it was pretty good, but at the same time more advanced programmers would realize more how much they really teach and what they miss out.
I have no idea with the discord import webhook , i usally just use requests like
requests.post(url, json=json)
```or discord_webhook is a bit eaiser , me personally i have no experience with that typa stuff
https://pll.harvard.edu/course/cs50s-introduction-programming-python?delta=0
The python class I mentioned earlier.
Well, when i was bored i took a look into it, which i already know enough python i would say, in my opinion the video wasnt bad but it was just very brief
Didn't you say you wanted to do it manually?
Yeah, but I was just looking through the discord docs and even trying this, it didn't work.
Lets learn some python 2😼
Can you link it to me? Looks sort of wrong, think webhook.send() needs to be awaited
Yeah.
Got any good beginner-intermediate tutorials that don’t go too deep but give a good example and explanation about each thing? I want to learn more. I have already made 2 projects with what I already know.
!resources have you seen any of these yet? pretty useful
Resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
@hazy isle you might be looking at an older version of the docs, this is what I'm seeing from the docs:
from discord import Webhook
import aiohttp
async def foo():
async with aiohttp.ClientSession() as session:
webhook = Webhook.from_url('url-here', session=session)
await webhook.send('Hello World', username='Foo')
Oh my god, I am sorry. I sent the wrong one. I found that other snippet in the discord.py
I've tried both what you posted and the other one I found.
What's the problem with this?
The other one you found seems to be from an older version
I set it up with the URL and just test what they have there. It just sits on the screen.
the cursor just blinks.
Did you use asyncio.run() to kickstart the event loop?
At the end of it, yes.
Hm. You're sure you're running the right file?
Oh, and it hangs for this version, not the other one?
One moment.
Thanks to you and @sick birch . I will most definitely use these resources to help me.
np
Do me a favour, try printing discord.__version__ to see what version you're on
I already had it open on the discord API wrapper.
__author__ = 'Rapptz'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015-present Rapptz'
__version__ = '1.7.3'```
you are amazing.
It's out of date.
I just updated it through pip now.

I am on 2.0.1 now....let's try this again. lol
IT WORKED! 
Thank you so much.

Check to make sure all packages are up to date.
This is how I learn best. Making mistakes!
I have an issue here. I don't understand how logging works apparently. On this example I get the logs to appear in the discord.log file but not on the console. How can I make it appear as well on the console?
log_handler = logging.handlers.RotatingFileHandler(
filename='discord.log',
encoding='utf-8',
maxBytes=5 * 1024 * 1024, # 5 MBs
backupCount=3) # Rotate through 3 files
bot.run(
token=hellodiscordiamnotthatdumbxD,
log_handler=log_handler,
log_level=logging.INFO)
```Then inside a cog:
```py
logger = logging.getLogger('discord')
logger.info("test to see if this works")
```What am I missing?
!d logging.StreamHandler
class logging.StreamHandler(stream=None)```
Returns a new instance of the [`StreamHandler`](https://docs.python.org/3/library/logging.handlers.html#logging.StreamHandler "logging.StreamHandler") class. If *stream* is specified, the instance will use it for logging output; otherwise, *sys.stderr* will be used.
make an instance of that ^ and it to your logger.
thanks
im trying to use a def func to provide default values for my bot.command cmd;
the problem is that if i put it above the bot call and define the returned value, its random variables r locked when the bot is started up.
how can i get around this ?
(this is a simplified example below)
def fruit():
fr = random.choice(['apple', 'banana'])
ch = random.choice(['1', '2'])
return fr, ch
fr, ch = fruit()
@bot.command(name='fruit')
async def selection(ctx, fruit=fr, num=ch):
ctx.send(fruit, num)
atm, itll just print the same thing repeatedly, as fr/ch is locked when the bot is launched
You could try to do something like this
@bot.command()
async def some_command(ctx, v1='auto', v2='auto'):
if v1 == 'auto':
v1 = random_value()
if v2 == 'auto':
v2 = random_value()
await ctx.send(f"{v1} {v2}")
If the input is auto then we'll generate or random it for them
hmm, this might work
I'm working with the guilded.py, but it seems to be based from the discord.py so why am I getting this error?
Context: I'm trying to change the name of the bot when it talks in chat
This channel is for help with discord bots, not guilded bots. You might wanna open a help channel, but seeing the error, it seems like you can't edit bot details from code
Ok
this isnt on topic, but i gotta say i like your pfp
Thanks!
i don't (🤢)
@tree.command(guild = discord.Object(id=test_server_id), name = 'start_game', description='Choose a game')
async def slash2(interaction: discord.Interaction, option: game):
await interaction.response.send_message(f"Command response {option}", ephemeral = True)
how do i pass a list as a parameter in a slash command game is a list i made
I don't think I understand what you're saying here
But I'm assuming you want to add a parameter option that gonna take the arguments as a list
yes
Afaik discord API doesn't support lists so you gotta do your own implementation
You can use * for that
@tree.command(guild = discord.Object(id=test_server_id), name = 'start_game', description='Choose a game')
async def slash2(interaction: discord.Interaction, *option):
await interaction.response.send_message(f"Command response {option}", ephemeral = True)
You also can take a look at https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py#L44
examples/basic_bot.py line 44
@bot.command(description='For when you wanna settle the score some other way')```
u can make a custom convertor
:thonk:
that basically make tuple of the strings u input by splitting at space
You might also mean autocomplete
it depends on his use case
shrike = self.client.get_user(923963169653784606)
embed = discord.Embed(
description=f"[**Official Discord Server**]",
color=0x9C84EF
)
embed.set_author(
name="shr!ke#0420",url= shrike.avatar.url```
set author url not working brother
Are you trying to use shrike.avatar.url as the icon of the author?
nvm
i had to use icon_url
Nice 👍
Alright, so I have this view, ```py
class ticket_panel(discord.ui.View):
def init(self, bot):
super().init(timeout = None)
print("0")
self.bot = bot
@discord.ui.select(
placeholder="Choose a ticket type...",
min_values = 1,
max_values = 1,
custom_id = "tickets",
options = [
discord.SelectOption(label = "Bot Development", emoji = ":bot:"),
discord.SelectOption(label = "Graphic Effects", emoji = ":gfx:"),
discord.SelectOption(label = "Server Creation", emoji = ":server:"),
discord.SelectOption(label = "Visual Effects", emoji = ":vfx:"),
discord.SelectOption(label = "Marketing", emoji = ":marketing:")])
async def ticket(self, select: discord.ui.Select, interaction: discord.Interaction):
member = interaction.user
and when I call it, it doesn't print 0 or b, only a, why? no erros btwpy
print("a")
view = ticket_panel(self.bot)
print("b")
where have you written this?
can you send the full file?
print("a")
view = ticket_panel(self.bot)
print("b")
ah guys how kick some one from a server?
discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'afk' raised an exception: TypeError: execute expected at most 2 arguments, got 3
did not work
I first tried bot-hosting.not, then replit.com.
Hm, you could try using a converter
!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`...
Wait
how do i delete a discord msg by reacting to it with a specific emoji?
I just see that you're using slash command
My bad
But I think you still can use converter
!d discord.on_raw_reaction_add
discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
payload is an instance of discord.RawReactionActionEvent. it likely has an emoji attr which you can use to check the emoji
And I probably get it wrong again
Just in case if you want something like this, you can use typing.Literal and take a look at https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/transformers.py#L87
examples/app_commands/transformers.py line 87
async def shop(interaction: discord.Interaction, action: Literal['Buy', 'Sell'], item: str):```
thanks for the help ill try it later
why it send me this error AttributeError: 'Interaction' object has no attribute 'joined_at' code py embed.add_field(name=f'Who Report User Join Time:', value=f"{interaction.joined_at.strftime('%h, %a, %#d %B %Y')}", inline=True)
add a try/except to handle that
It will happen if a user tries that cmd in dm for example
ok
@commands.hybrid_command(
name="afk",
description="Set your status to AFK.")
@checks.not_blacklisted()
async def afk(self, context: Context, reason: str = None) -> None:
"""
Set your status to AFK.
:param context: The hybrid command context.
:param reason: The reason for being AFK.
"""
member= context.author
if reason is None:
reason = "No reason provided."
await self.client.db.execute("INSERT INTO afk (user_id, reason) VALUES ($1, $2)", context.author.id, reason)
await context.author.id.edit(nick=f"[AFK] {context.author.display_name}")
await context.send(f"**{member.name}#{member.discriminator}**, You are now AFK : {reason}")```
discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'afk' raised an exception: TypeError: execute expected at most 2 arguments, got 3
For some reason when I call my function, everything stops.```py
class ticket_panel(discord.ui.View):
def init(self, the_bot):
super().init(timeout = None)
print("0")
self.the_bot = the_bot
@discord.ui.select(
placeholder="Choose a ticket type...",
min_values = 1,
max_values = 1,
custom_id = "tickets",
options = [
discord.SelectOption(label = "Bot Development", emoji = ":bot:"),
discord.SelectOption(label = "Graphic Effects", emoji = ":gfx:"),
discord.SelectOption(label = "Server Creation", emoji = ":server:"),
discord.SelectOption(label = "Visual Effects", emoji = ":vfx:"),
discord.SelectOption(label = "Marketing", emoji = ":marketing:")])
async def ticket(self, select: discord.ui.Select, interaction: discord.Interaction):
member = interaction.user
channel = interaction.channel
print("1")
async with self.the_bot.db.acquire() as con:
print("2")
async with con.cursor() as c:
print("3")
await c.execute("SELECT * FROM Tickets WHERE memberid = %s", (member.id,))
print("4")
It doesn't even print 0.
why this not working
{('%a, %#d %B %Y')}
What should it do..?
Then just do await ctx.send(datetime.now())
datetime.datetime.now()
You need to install it pip install datetime and import datetime.
import it?
ok
this not wokring embed.add_field(name=f'Time', value=f"{datetime.datetime.now()}", inline=True)
no error but it not show
@slate swan
That's because you have to get the user from the interaction first
!d discord.Interaction.user
The user or member that sent the interaction.
Ok!!
!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.10)") since it is an aware datetime, compared to the naive datetime in the standard library.
New in version 2.0.
How do you call your function
they are almost the same thing
https://github.com/Rapptz/discord.py/blob/master/discord/utils.py#L737
discord/utils.py line 737
return datetime.datetime.now(datetime.timezone.utc)```
I'm trying to make a guard bot with discord.py and there is a place where I'm stuck. How can I reinstate the updated value on channel and role updates?
datetime is a module?
not a library, its a stdlib
ah why this not work py if self.name2.value content "https://discord.com/channels":
what are you trying to do?
do you mean, contains?
yees
!e you can do something like this
string = 'hello'
if 'h' in string:
print('yes')
@paper sluice :white_check_mark: Your 3.11 eval job has completed with return code 0.
yes
OOOh in
the single word “contents” completely made my brain go numb to everything else in the question trying to figure out what that was
ok now how check if 'h' isn't in string
not in
:0 what a smart guy
lmao
are you sure this should work? if self.name2.value not in "https://discord.com/channels":
when i put message link like [#discord-bots message](/guild/267624335836053506/channel/343944376055103488/) it say you can't
and it should can bc this in the self.name2.value
OHHH
sorry me dumb 🙂
Thank You for your time!!
I'm trying to make a guard bot with discord.py and there is a place where I'm stuck. How can I reinstate the updated value on channel and role updates?
hello how can i send multiple strings in a codeblock to discord through bot
tried different things it just types the string names.
why if "https://discord.com/channels" or " " not in self.name2.value: not working
or " " isn't working
!or
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
print("b")
view = ticket_panel(self, self.bot, "d")
print("C")
it checks if self.name2.value's identity is equal to set
Did you updated your ticket_panel class?
wdym?
I see that you're putting self and d in the call
view = ticket_panel(self, self.bot, "d")
But your view only take 1 argument
Yeah, I tried to see if it would give an error. For some reason it didn't.
Hm
It doesn't work with 1 argument either.
The thing is that it worked before, then I changed database and now it isn't working. Even tho I'm not using the database in that command.
Where do you call it?
In a slash command, it executes everything until the call, then it quits without an error and all the code below stays un-executed.
Found the problem
I accidently overwrote the function by assigning a variable with the same name. 🤦♂️
👍
@bot.command()
@commands.has_permissions(manage_roles=True)
async def mute(message, member: discord.Member, sure:str):
role = discord.utils.get(member.guild.roles, name='Muted')
await member.add_roles(member, role)
embed=discord.Embed(title=f"{member.name} muted", color=0xff00f6)
await message.send(embed=embed)
await asyncio.sleep(sure)
await member.remove_roles(role)```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10011): Unknown Role
there is a role named Muted and its not above the bots role
can somebody help me?
add_roles() doesnt take a member object
mhm
it works now but it didnt remove the role after 5 sec
(sorry for ping)
is there something wrong with await member.remove_roles(role)?
hm im sure that sure should probably be typed with int/float since you're passing it to asyncio.sleep()
i mean, sure, but you already have it as a command parameter, just replace the typehint and let dpy convert it for you
howdy, i use my raspberry pi 3 to host a discord bot, i also plan on hosting a website with it
i was wondering if getting an external ssd for it would be beneficial, it would run on it instead of the micro sd card
this...isn't the correct channel?
Depends on the size of your bot and website
And considerations like a database
And possibly reliability, storing frequently read and written data on an SD card is more likely to result in data loss than something like an external drive designed for that sort of operation, but on the flip side, good backups should remove this from being any more of a problem than needing a new SD card
yep
I can't use the setup_hook 'cause no and syncing inside the method I use Bot.start in, results in a missing app id error
yea, idk why you can't use setup hooks but, setup_hook is called in login so you might as well
you could do something similar to setup_hook subclassing commands.Bot and overwriting the start method (make call to your setup_hook function and then call the original start method with super().start(...))
I tried that, doesn't work
yeah, ig that will do
thnks
bot.py lines 66 to 76
async def start(self, *, reconnect: Optional[bool] = True) -> None:
logging.info(f'Starting the bot at {datetime.utcnow()}')
# This function is similar to a Setup_hook function
# Load an setup here database connections etc...
self.load_exts()
await self.load_json_info()
self.uptime_start: datetime = datetime.utcnow()
self.add_persistent_views()
await super().start(self.TOKEN, reconnect=reconnect)```
hello everyone, I have a question how to do so that after the bot sent a message and you answered it through the "reply" button, I sent the following message, and when I just wrote without the "Reply" button, I did not answer anything
I need to sync the commands smh
Am I having a stroke
you can use asyncio.create_task, but why not use setup_hook?
'cause no
?

why is it Optional [bool] when the default value is a bool?
jeez im dumb
no actually im not
a parameter is optional when it have a default value setted, not when it's None
the copy function for embeds is kinda useful in dpy
wrong
!d typing.Optional
typing.Optional```
Optional type.
`Optional[X]` is equivalent to `X | None` (or `Union[X, None]`).
Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the `Optional` qualifier on its type annotation just because it is optional. For example:
```py
def foo(arg: int = 0) -> None:
...
``` On the other hand, if an explicit value of `None` is allowed, the use of `Optional` is appropriate, whether the argument is optional or not. For example...
copy()```
Returns a shallow copy of the embed.
but mypy doesn't cry about it
so useful ngl
it won't cry because it thinks the value provided by the user can be None as well, as mentioned its not related to the default value at all
and its set to a bool, so why would it have an issue
yeah... helps to create similar embeds
that's not the part where it shod cry, reconnect kwarg accepts only bool so he should cry in that sense
your mypy is drunk
def foo(x: int): ...
def bar(x: int | None = 69): foo(x)
this optional stuff is always very irritating
iirc mypy has some implicit and explicit optional config method use that
🚶♂️ it keeps you safe from dumb discord.py cache issues
what..
so in short u want to check if ur message was replied to right?
ur explanation is sorta confoosing
Yeah, sorry, what did you mean 
translator troubles. Can not do anything
!d discord.Message.reference
after switching from Windows to Mac, i've been getting an error where, when i interact with a button, i get an error. I have no clue how to fix it..
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/bot.py", line 1058, in on_interaction
await self.process_application_commands(interaction)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/bot.py", line 722, in process_application_commands
) and isinstance(interaction.data, interactions.ComponentInteractionData):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/typing.py", line 2385, in __subclasscheck__
raise TypeError('TypedDict does not support instance and class checks')
TypeError: TypedDict does not support instance and class checks```
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
if this is not None it means it was a reply
still new to python
@client.command()
async def redeem(ctx, message:str):
tokens = {
"TIUiPjep4t",
"bkAZQoZlTc",
"rRLQJ9oKVz",
}
if tokens in message:
await ctx.send("token found")
else:
await ctx.send('Token not found')
discord is frustrating me with their buttons
you can put 5 emoji buttons in a row but ofc it cuts off at 4 on mobile
got too many rows already
how do i grab the username of user who sent message in a channel?
in on_message event?
message.author
lovely thank you 🙂
discord.player: ffmpeg process 44 successfully terminated with return code of -11.
how to fix this irritating error
anyone?
Are they global, and are they synced?
it is working in my testing server of slashcommands
but the slash commands are not appearing in other servers
yes
i synced that
global ?
oh how to globally sync them ?
aah that's why they are not appearing in other servers
ok
wait sharing my code
how would i put current time in embed footer? 🙂
await bot.tree.sync(guild=discord.Object(id=936466653271691265))
print("Synced")
i am syncing like this
what to change here?
await bot.tree.sync()
ok
@bot.hybrid_command(name="ban", with_app_command=True, description="Ban a Member from this Server")
@app_commands.guilds(discord.Object(id=936466653271691265))
@commands.has_permissions(ban_members=True)
async def ban(ctx):
pass
this too ?
yes i believe so
class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)```
The *year*, *month* and *day* arguments are required. *tzinfo* may be `None`, or an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass. The remaining arguments must be integers in the following ranges...
should i remove that guilds line ?
Not exactly
they should be instant uppon syncing/registering now
it was told in discord.gg/discord-developers i believe
do you mean i can see the change instantly ?
They should, yes
iirc the "try my commands" part is for verified bots only
discord lists them based on popularity
my bot is verified
!e
my_tup = ("hello", "world", "element 3", )
print(my_tup[10])
@sick birch :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | IndexError: tuple index out of range
@sick birch ever since setting up your Mac have you ever gotten a TypedDict error?
Guys, say, if I wanted to import a variable from one file to the other, what should I do?
from file import file.variablename?
you are trying to access item from tuple that doesnt exist
!e
print(int('hello'))
@paper sluice :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 | ValueError: invalid literal for int() with base 10: 'hello'
how do i make my bot read a text file and say whats in it?
you should know that.
Pretty vague question so lemme rephrase.
I want to
""" Topic """
@commands.command(name="topic")
async def topic(self, ctx):
Responses = Very Long List of Topics
embed = disnake.Embed(title="", description=f":BA: {random.choice(Responses)}", colour = disnake.Colour.random())
embed.set_author(name=f"Requested by {ctx.author.nick}", icon_url=f"{ctx.author.display_avatar}")
await ctx.send(embed=embed)
await ctx.message.delete()
Instead of putting the Responses in the Current file, I want to transfer a variable from a different file to this cmd right here. I tried
from file import file.variablename but it just said these (Picture)
from file import variable
Aight lemmet ry
rip
It worked. thx for the help!
nope, these are basic things you should know by now, but you don't because every time someone tries to help you by sending you to docs or a tutorial , you simply ignore it and ask people to write code for you.
Is there a way to access variables from files which are inside a folder with a hyphen? Tried doing it like this From File-Name.Variable import Responses but it didn't work lol
Asking this just out of curiosity
Seems like it works if I remove the hyphen
like, from folder.file import object
then you can't do that
the folder name must follow the same rules as naming a variable or function
so _
yea
lol. Gothchu
!pip aiofiles
ty
Would someone be able to point me to how discord.py handles events internally? I'm mostly interested in what happens starting from when the gateway dispatches, for example, a MESSAGE_CREATE event to you
@sick birch
discord/client.py line 429
def dispatch(self, event: str, /, *args: Any, **kwargs: Any) -> None:```
discord/client.py line 418
def _schedule_event(```
hey guys vs code acting weird. i import smth from my own file and it works but now i import the same thing just with another name and it wont work
can i have some help pls
nvm i forgot to save it lol
Wdym with another name
ye like this
test = "test" test2 = "test"
but i forgot that you need to click ctrl + s in vs
Why would you create another pointer?
bruh nvm guys i was just wondering why but i found it
i forgot to SAVE it
because i use VISUAL STUDIO
autosave is a feature
pointers are tasty 😋
nullptr tastes like water
and you can't survive without it
@client.command()
async def redeem(ctx, message:str):
tokens = [ "TIUiPjep4t", "PtBVrRBVWv", "7Nkpp9IIpn", "oDM62ZQXsF", "RrSnyx9aXU"]
if tokens in message:
await ctx.reply(f"`{tokens}` is now redeemed.", mention_author=False)
else:
await ctx.reply('Token not found')
not sure why this isnt working
still new to python
i think you want to iterate over the list, and check if the item of the list is in the string
you mean if message in tokens lol
or that
ok
I like the dialogue "I am new to Python" idk why
That really shouldnt be an excuse to jump to an advanced library either
im just making stuff that i need for what i want to do with the bot
Thats like saying, I did my own heart surgery because i needed it
Nice
i love doing my own heart surgery
fr
The tapeworms are so cute ☺️
Arent tapeworms, worms that come from your behind?
How does that have any relation to your heart
no tapeworms can be anywhere in your body
['TIUiPjep4t', 'PtBVrRBVWv', '7Nkpp9IIpn', 'oDM62ZQXsF', 'RrSnyx9aXU'] is now redeemed.
thats what it says
Yea because that's what you're telling it to send
what should i change
What do you want to send
So which variable is storing the token
tokens
No, tokens is storing all the valid tokens
Which variable is storing the token given by the user
Which is what you want to send
hello
i joined the server to get help figuring out what wrong i have done on my discord bot code
if anyone could help me
Ask away
i have everything setup, but im still getting error messages for every command i use
i have went back through all the code for like 11 times and i cant find what wrong i have done
Would be helpful to see the error message
its my first day coding in here
Jumping into discord.py is probably not a good idea then
if you need help on learning the given concepts and topics check out:
Learning basic python: https://realpython.com/tutorials/basics/ https://www.youtube.com/watch?v=YYXdXT2l-Gg&list=PL-osiE80TeTskrapNbzXhwoFUiLCjGgY7
Learning asynchronous programming and its implementation in python: https://www.youtube.com/watch?v=Xbl7XjFYsN4&list=PLhNSoGM2ik6SIkVGXWBwerucXjgP1rHmB
Learning python's OOP: https://www.youtube.com/watch?v=ZDa-Z5JzLYM
uhm
material
i understand i fixed it thank you
im not really new to python
like i took the class on my first sem this year on college
then skip the step!
im already used to it
Hello
but its my first day coding a discord bot
Because it’s an advanced library and not meant for newcomers
aha
i just wanted to code a bot that counts a virtual points
with add, remove and balance command, and it felt like it would be normal
but its not, using too many external functions
would you like to see what doesnt work ?
How else could I help lol
Psychokinesis
I have a feeling I know where this is going
but it works fine runnning it on cloud
Send the error please
Otherwise it’s impossible to tell what’s wrong (though I have a hunch)
inb4 json
I unfortunately can’t read minds
json?
JavaScriptObjectNotation
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.
Also the error might be more useful
And the error?
import disnake
import datetime
from disnake.ext import commands
intents = disnake.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(
command_prefix=commands.when_mentioned_or("?"), description = "", intents=intents
)
####################################### anty reklama #######################################
# słowa, których nie można używać na serwerze:
zabronioneslowa = ['https', 'http', 'www', 'discord.gg', 'd.gg']
@bot.event
async def on_message(message):
if message.author.id == bot.user.id:
return
msg_content = message.content.lower()
curseWord = zabronioneslowa
if any(word in msg_content for word in curseWord):
await message.delete()
embed = disnake.Embed(title="OSTRZEŻENIE!", description="Nie możesz reklamować się na serwerze!", colour = 0xFF0000, timestamp = datetime.datetime.now())
embed.set_footer(text="© Rynek", icon_url="https://cdn.discordapp.com/attachments/1016070336678207520/1016438417187422218/SAVE_20220713_173556.jpg")
await message.author.send(embed = embed)
####################################### propozycje #######################################
@bot.command()
async def test(ctx):
await ctx.send("supa")```
why bot.command not working?
only client.event
?
i mean in their code
Im still not catching on, your choice of words is quite poor
Guys this error local variable 'myview' referenced before assignment and this code await interaction.send("Pick your favourite colour:", view=view and myview, embed=embed, ephemeral=True)
view and myview? :huh:
what should that do?
it will return a bool obj
um buttom1.callback = buttom1_callback buttom2.callback = buttom2_callback buttom3.callback = buttom3_callback myview = View(timeout=180) myview.add_item(buttom1) myview.add_item(buttom2) myview.add_item(buttom3) myview2 = View(timeout=190) myview2.add_item(buttom12) myview2.add_item(buttom22) and ```class Dropdown(nextcord.ui.Select):
def init(self):
options = [
nextcord.SelectOption(
label="Red", description="Your favourite colour is red", emoji="🟥"
),
nextcord.SelectOption(
label="Green", description="Your favourite colour is green", emoji="🟩"
),
nextcord.SelectOption(
label="Blue", description="Your favourite colour is blue", emoji="🟦"
),
]
super().__init__(
placeholder="Choose your favourite colour...",
min_values=1,
max_values=1,
options=options,```
Wait did nextcord steal my code
Ye
lol
after switching from Windows to Mac, i've been getting an error where, when i interact with a button, i get an error. I have no clue how to fix it..
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/bot.py", line 1058, in on_interaction
await self.process_application_commands(interaction)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/bot.py", line 722, in process_application_commands
) and isinstance(interaction.data, interactions.ComponentInteractionData):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/typing.py", line 2385, in __subclasscheck__
raise TypeError('TypedDict does not support instance and class checks')
TypeError: TypedDict does not support instance and class checks```
@silk fulcrum
he deleted everything 😔
Is it possible to do a loop, but it doesnt do an initial run?
coz whenever I start a loop it always does an initial run
what loop is it?
any helpp??
tasks.loop
oh, i was thinking about something completely different xD
yeah lol
D:
how do i make my bot execute a command?
I'll make this quick since I'm sleepy as hell. How can I loop through a list? I want to loop through this list of Activities. But I just can't figure out how.
So far, I have this:
Activity = ["Activity 1", "Activity 2", "Activity 3"]
bot = commands.Bot(
command_prefix=",",
intents=intents,
status=disnake.Status.idle,
activity = disnake.Activity(type=disnake.ActivityType.watching, name=random.choice(Activity))
Tried for loops but I couldn't figure it out lol.
Still getting used to loops and stuff
If I don't reply back, assume I went to sleep lol. I'll figure this out myself inthemeantime
You want your bots status to change periodically?
Yes. That
You probably want to set up a @tasks.loop
And then do what you’re already doing in there
There are a few examples in the docs page for it
This one?
@tasks.loop()
async def status_task() -> None:
await bot.change_presence(status=STATUS-HERE, activity=ACTIVITY-HERE)
await asyncio.sleep(TIME)
Found it on stack overflow lol
Can u send the link?
This is bad lol
Just pass in the loop interval to the decorator
!d discord.ext.tasks.Loop
class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.
The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
Noted. I'll try this out. Thanks!
thats the error @ robin
i just invited the bot again, i had to change couple things in the settings
Btw, it said tasks is not defined?
This is what happens when unexperienced people try to earn upvotes on stack
any reason this command isnt work? @client.command @commands.has_permissions(kick_members=True) async def warn(ctx, member: discord.Member, *, reason="Not Specified"): if member == ctx.author: await ctx.send("You cannot warn urself!") else: em = discord.Embed(title="**WARNED**", description=f"{member} was warned because: {reason}", color=discord.Color.red()) em2 = discord.Embed(title="**WARNED**", description=f"You have been warned because: {reason}", color=discord.Color.red()) await member.send(embed=em2) await ctx.send(embed=em)
What’s the error say?
no error
same thing
just dnt work
i cant get it it
i have read my code for like 15 times
i dont even get any errors
python3 main.py
main.py:108: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension(f'cogs.{filename[:-3]}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2022-09-07 19:26:25 INFO discord.client logging in using static token
2022-09-07 19:26:26 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: ce34398c05275ab9630e687e180edf21).
Connected to discord as Spendy#1904
await bot.load_extension
what about it
await bot.load_extension
how to fix my issue
thats my code, i have returns and await on most of them
line number 38, 54 and 59
thats another doc on my project
yeah i fixed it but still the same
thats the log now
im really confused
@dark pine I'm still not sure what the issue is
im tired of this, its really difficult even tho i have done other codes with many backtracking n stuff
but this one seems really simple to add,remove, and balance commands but its really complicated
like
does anything seems wrong on my points commands?
the issue is that im still scrolling inbetween the functions
i dont see anything wrong, in addition to that i got no errors, not sure whats wrong with it sadly its my first day into discord bots 😦
how can I send an embed if an error occurred? d.py 2.0 and slash command
tried it like this:
embed = discord.Embed(colour=728634, title="Error!")
embed.add_field(name="Verfügbare Stores", value='')
await interaction.response.send_message(embed=embed)```
So in my cog I have a function thats suppose to loop but i only want to start it once my interaction completes.
The interaction is a nested class inside of the cog.. i keep getting an error saying "self" was not included...
How can I start the loop?
@sick birch any other thing for payment?
not stripe?
i tried using patreon but they're bot its just offline
so it won't be able to give roles to users
Stripe, paypal, patreon, gofundme, kickstarter? idk what type u need or why, but heres a few
then there's american/international like venmo?
i think it's venmo
stripe requires bank IBAN
errorchannel = await interaction.guild.get_channel(channel id)
#embed stuff here
await errorchannel.send(embed=embed)
await interaction.response.send_message("There was an error. check the error channel", ephemeral=True)
it doesnt reply as i coded it
doesnt respond to any command
my points code: https://paste.pythondiscord.com/yebecazaki
coz .add and .remove arent commands.
my prefix is . and remove + add are commands
using @commands.command, the function name acts as the command in discord.
so in this case: .points would be a command.
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
commandname = str(ctx.command)
commandauthor = ctx.author
channel = self.client.get_channel(self.config["error_channel"])
tb = traceback.format_exception(type(error), error, error.__traceback__)
commandrun = ""
for i in tb:
commandrun += f"{i}"
with open("error_log.txt", "w") as f:
f.write(commandrun)
with open("error_log.txt", "rb") as f:
await channel.send(
content=f"Command Name: {commandname}, Author: {commandauthor}",
file=discord.File(f, filename="error_log.txt"),
)
where to add dat on
anywhere.
it'll work for the whole bot. i made a new cog for it
Hey @drifting arrow!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
with except app_commands.errors: ?
i think so?
if not, just use tb = traceback.format_exception(type(error), error, error.__traceback__) and for i in tb: print(i)
what should the inp should be here?
right click a channel in your discord -> copy id
aha, then to paste it?
ok it runs now, to try and type the commands in?
sure
yeah i was confused how you convert it to int
you should get an error
i got a config file that looks like this
This config hasnt got the error handling
gimme a second
no worries, i can share my screen on a code/help vc if its easier
sorry about the questions, its my first day
wheres the code that sends "There was an error" lol
into discord bots*
hopefully i didnt make a big mistake XD
its the thing you have sent XD
i removed the catch error one and im getting errors now
see
there we go.
paste this into your cogs file.
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
commandname = str(ctx.command)
commandauthor = ctx.author
channel = self.client.get_channel(123)
tb = traceback.format_exception(type(error), error, error.__traceback__)
commandrun = ""
for i in tb:
commandrun += f"{i}"
with open("error_log.txt", "w") as f:
f.write(commandrun)
with open("error_log.txt", "rb") as f:
await channel.send(
content=f"Command Name: {commandname}, Author: {commandauthor}",
file=discord.File(f, filename="error_log.txt"),
)
and remove any other on_command_error code
and make sure you import traceback import traceback
its not an error logger so it should be send in the channel where the command was used or when the command was used in dms then there
Not necessarily.
if the error happens in a general chat with lots of chatter, do you really want the error to fly off into oblivion?
and it's useless being sent to a random user. why would they report it?
so send it to a discord channel
so now to use the command?
yes
webhook will only be visible to the command user ofc
We arent using webhooks?
same thing as before
but this time your error appeared in the target channel 🙂
Read the traceback and find out what you're doing wrong.
wait, should i keep these at main?
do you have a function called points or hel? or did you assign an alias to any function(command) called points or hel
i got this file in cogs:
its for all the points settings
i got em in one class
reading ur code now,
oh sorry
im confused as to what the category thing is anyway
the cogs might be more organized here
XD
all i wanted to code is a bot with add, remove and balance commands
for imaginary points
discord embed
your main.py isnt actually loading the cogs..
Hey!
I have a def that if it is true it does something, and the information is in a .json file, How would i def it in my main file?
def botlogging(ctx):
return str('whatever i need here' in settings ["botlogging"]
0.0
how?
i've import em
hello guys please help me with this erreur
intents = discord.Intents().all()
bot = commands.Bot(command_prefix='>', intents=intents)
and go to discord developer portal and enable all bot intents
Discord Developer Portal
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
tysm bro
np
❤️
❤️
if you want to edit a json file, it's:
with open('myjson.json', 'w') as f:
f.write(json.dumps(myvariable, indent=4))
```is it dumps? or dump? i forget. I always reference my code.
I know one of them spits out error
im still confused as to what you want.
i want to def botlogging
when working with a json file you first have to load it into a variable. then you do your editing to it, then you save it
but in a .json file i have if it is true or false
thats what i have
but i want to def botlogging in my main file
how would i get that info
like i have
def Staff(ctx):
return str(ctx.author.id) in settings["staffId"]
myfile = ''
with open('myjsonfile.json', 'r') as f:
myfile = json.load(f)
if myfile['botlogging']:
myfile['botlogging'] = False,
with open('myjsonfile.json', 'w') as f:
f.write(json.dumps(myfile, indent=4))
then send it to the main self so create a variable in the init, called self.myfile or whatever. idc. and load the json file there
then to reference it later, do self.myfile etc
and if you want to update it, self.myfile = ...
thanks
alright.
now that I've gotten those nerds out the way. can someone help me with my issue? 😄
probably a bit more complex than what you can handle but sure I'll shoot it.
I have a child class and I am trying to target the parent class and start a loops event xD
had to reply to someone.
yep to complex, sorry
guys my bot i showing link of picture in message why ? i want only picure without link
i dont need link in message
who can help me please
how would i check
say like a string is 5e712ecf-2fbb-4f37-a462-155917378803 , how would i check how many "-" are in said string
alright thx im gonna try
Thank you !
can u send me code that i need to add ?
im new in python I do not understand
@bot.command()
async def image(ctx):
await channel.send(file=discord.File('my_image.png'))
ty
forgot the @bot.command() fixed above
how do i make my bot delete my command ?
?
when i send command like !image he send command and he delete my message of command
im not good at english
await ctx.message.delete()
Uh, try putting this on top of the command
await ctx.message.delete()
alright thx
i like that you refer to the bot as “he”
English may not be their first language. Plenty of languages, like French, assign genders to most of their words
XD
oh nah i do the same thing
it was just funny to see in context
How do I change this info
The server's description?
!d discord.Guild.edit
await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., afk_channel=..., owner=..., afk_timeout=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the guild.
You must have the [`manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") permission to edit the guild.
Changed in version 1.4: The `rules_channel` and `public_updates_channel` keyword parameters were added.
Changed in version 2.0: The `discovery_splash` and community keyword parameters were added.
Changed in version 2.0: The newly updated guild is returned...
??
Hm? 🤔
I am trying to get the status of a user to see if that user is online (my other bot), however that status it returns is a class type. How can I convert the class to a string to show the value in my if statement. Any ideas?
@tasks.loop(seconds=5.0)
async def printer():
## DEFINES USERS // CHANNELS
guild = StatusBot.get_guild(1014394890748178432)
channel = StatusBot.get_channel(1017200174914879609)
DaveModPremium = guild.get_member(1013496497603625011)
DaveMod = guild.get_member(998302501356974220)
print(type(DaveMod.status))
print(type(DaveModPremium.status))
print(channel)
##SENDS ALERT IF BOT IS DETECTED OFFLINE
if DaveModPremium.status or DaveMod.status != 'online':
print(DaveModPremium.status)
await channel.send(f'{DaveModPremium.mention} is Offline!')
print('DaveModPremium Is OFFLINE!')```
You can use str() for that
@tasks.loop(seconds=5.0)
async def printer():
## DEFINES USERS // CHANNELS
guild = StatusBot.get_guild(1014394890748178432)
channel = StatusBot.get_channel(1017200174914879609)
DaveModPremium = guild.get_member(1013496497603625011)
DaveMod = guild.get_member(998302501356974220)
print(type(DaveMod.status))
print(type(DaveModPremium.status))
print(channel)
##SENDS ALERT IF BOT IS DETECTED OFFLINE
if str(DaveModPremium.status) or str(DaveMod.status) != 'online':
print(DaveModPremium.status)
await channel.send(f'{DaveModPremium.mention} is Offline!')
print('DaveModPremium Is OFFLINE!')```
Or you can also use `isinstance()`
It's up to you
ive tried str() but it does not seem to return the expected results. I will try out the isinstance() method as you mentioned though
and str() returns <class 'discord.enums._EnumValue_Status'>
Hmmmm
help please
i think that is my own issue, one moment
Maybe you could try something like
DaveMod.status != discord.Status.online
If isinstance don't work
ah that would work well
Can you show the code
ive give it a go, thanks
Hey @slate swan! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
You can have a look at https://stackoverflow.com/questions/65101859/discord-py-check-member-status
import discord
from discord.ext import commands, tasks
from datetime import datetime
intents = discord.Intents().all()
bot = commands.Bot(command_prefix='!', intents=intents)
@tasks.loop(seconds=60)
async def task():
now = datetime.now()
current_time = now.strftime("%H:%M %p")
await bot.change_presence(status = discord.Status.online, activity = discord.Game(f' With Misk1'))
@task.before_loop
async def before_loop():
await bot.wait_until_ready()
print('Ready')
task.start()
@bot.command()
async def Server(ctx):
await ctx.message.delete()
await ctx.send("** Server is online have fun ! @everyone **")
@bot.command()
async def image(ctx):
await ctx.message.delete()
await ctx.send("https://media.discordapp.net/attachments/1002356883899826258/1017156567818313791/Untitled-122.png")
@bot.command()
async def ip(ctx):
await ctx.message.delete()
await ctx.send("Fivem ==> Console (F8) ==> Copy/Past ==> Connect 92.42.45.132:30120 ")
bot.run("") ```
ah thanks, i searched for a while but couldnt find anything. huge help!
so ?
Well, it looks like the error is saying that
await ctx.send(...)
line isn't in the same indent as the
await ctx.message.delete()
hm even with this is still isnt working.. I dont understand why but it does not seem to think that user.status is the same type as discord.status (as it always shows offline in the if statement, but the actual status from user.status shows online)
Can you show the code that check the status again?
if DaveMod.status or DaveModPremium.status != discord.Status.online:
print(DaveModPremium.status)
#await channel.send(f'{DaveModPremium.mention} is Offline!')
print('DaveModPremium Is OFFLINE!')```
ty
indent is wrong because of discord
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
im not, im checking the status (it is my other discord bot, i am making a separate bot to detect when the bot goes offline.)
ahhhh
i seee
I had a good feeling thats where it went wrong
thank you for that, ill give it another go
say if i forked discord.py & used that fork instead of the official one.. What are the cons if there are any
You will have to maintain your fork if you want to keep using it instead of discord.py
By customizing your installation or forking the library, uppon updating its state would probably be erased so your edits would be erased, over overwriting methods in your code and only have future compatibility issues
But since dpy almost never edits its old codebase the compatibility issues would be rare, but as i++ has said, your custom installation wouldnt be up to date or compatible for future projects with other original installations depending on the implementation of future endpoints so you would need to continue to maintain it
does anyone know how to get context menu in a cog discord 2.0?
Sure. I recently made a PR regarding just that
how do i delete a msg when someone reacts to a msg sent by my bot? ive worked out how to add the emoji, now i want to delete the msg if someone reacts with that emoji
i think its related to on_raw_reaction_add() but im not having much luck through google
use Bot.wait_for and wait for that event, and then you can delete the message
oh wait, which message do you want to delete when someone reacts?
so if i ctx.send("apple") and add an apple emoji to it, i want the "apple" msg to be deleted
if someone reacts to that msg with an apple emoji
ok, so in that command itself you just do bot.wait_for('on_reaction_add', check=<your check function>)
and in the check function, you check if the message they reacted to is the one sent by the bot basically
and you can check for emojis as well
so... id need to write it as a new command?
or put it under the one that made the msg
just under that
ah
https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for
there is an example here
so itd be like
async def fruit(ctx):
apple = "apple"
ctx.send(apple)
# add emoji stuff
bot.wait_for(on_reaction_add, check=check)
if ... == True
ctx.message.delete()
?
you want to delete the apple message right
yes
so store it in a variable and delete that, ctx.message is the message which was used to call the command like !fruit
ah
and .delete() is a coro, so await it
not sure i follow u there
the ctx.message part i get
just like this
msg = await ctx.send(...)
...
await msg.delete()
ah
async def fruit(ctx):
apple = "apple"
message = await ctx.send(apple)
# add emoji stuff
bot.wait_for(on_reaction_add, check=check)
if ... == True
await message.delete()```
yeah i got this rn
msg = await ctx.send(f"...")
await msg.add_reaction('⚔️')
so i alrdy got a variable that refers to it right
yep
just make sure the bot has permissions to add reactions or you might run in errors
do i need on_reaction_add in a str?
yeah
why ?
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
if this wait_for never times out, does that mean that if i spawn a ton of these msgs that ill clog up my system?
if i dont set a timeout
well you will probably get a temp ban from the Discord Api before that happens hehe
and also, i presume that when i restart the bot to update something, the emoji-delete wont work either right
Yeah
seeing as its within a func
thought so
maybe i could set it to auto-delete after it times out
Can someone guide me to some resource where i can get help with the API rate limit i am running into frequent bans so was looking for ways to get the bot operations in limits
yeah i was looking there b4

