#discord-bots
1 messages Β· Page 575 of 1
property roles: List[discord.role.Role]```
Returns a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of the guildβs roles in hierarchy order.
The first element of this list will be the lowest role in the hierarchy.
@vapid trellis @slate swan @slate swan DONE!
try something like this -
split = list(text)
i = len(split)
l = []
for j in range(0, i):
spoiler = "|" + split[j] + "|"
l.append(spoiler)
s = ''.join(l)
await ctx.send(s)
async def spoiler_cmd(self, ctx, *, text=None):
if text is None:
await ctx.reply("What do you want me to say?", mention_author=True)
else:
parsed_args = "||||".join(text)
await ctx.send(f"||{parsed_args}||")
see my code
done done
Great but dont ping us some people dont like it
it worked?
noice
yes
I dont mind but some people do
glad it works
ty bro
why am i getting this error;
Traceback (most recent call last):
File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\coolb\OneDrive\Documents\mootbot\cogs\Commands.py", line 337, in resetcooldown
await partner.reset_cooldown(ctx)
NameError: name 'partner' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'partner' is not defined
when i run this command
@commands.command(name="resetcooldown")
@commands.has_any_role("Staff")
async def resetcooldown(self,ctx,member: discord.Member=None):
await partner.reset_cooldown(ctx)
await ctx.send("Reset")```
in reference to this command:
```py
@commands.command(name="partner")
@commands.cooldown(1, 21600, commands.BucketType.user)
async def partner(self,ctx,member: discord.Member=None):```
It would be await self.partner().
as in
@commands.command(name="resetcooldown")
@commands.has_any_role("Queer")
async def resetcooldown(self,ctx,member: discord.Member=None):
await self.partner.reset_cooldown(ctx)
await ctx.send("Reset")```
?
correct.
gives me
Traceback (most recent call last):
File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\coolb\OneDrive\Documents\mootbot\cogs\Commands.py", line 337, in resetcooldown
await self.partner.reset_cooldown(ctx)
TypeError: object NoneType can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\coolb\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object NoneType can't be used in 'await' expression
hey guys, so I have been trying to retrieve the member info using this command -
member = discord.utils.get(guild.members, name="KamiKaizen")
but I was wondering if I could do the same with the member id instead of the member name
or is there a way to retrieve the member name if the id is known
u can use member = await bot.fetch_member(id)
aight lemme try that
dont, thats an api call
wdym
what are you trying to do
fetch x is an api call and if used on a large scale can get your bot rate limited
and takes a long time
compared to other solutions
oh, I see. I didnt know about that
what are you trying to do
they want to get the member object using the member id
use a typehint
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
Ah, well yes. If its a command, typehinting is the best way
what I'm trying to do is alter the vc permissions, something like -
m = discord.utils.get(guild.members, name="KamiKaizen")
vn = discord.utils.get(guild.channels, id=f)
await vn.set_permissions(m, connect=True)
so I tried it, and this is what I get -
m = discord.Guild.get_member(user_id=h) TypeError: get_member() missing 1 required positional argument: 'self'
Breh, u need an instance of discord.Guild
!d discord.Client.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
@urban shellis it a command or a seperate function??
not literally discord.Guild an instance, most common is ctx.guild
and mising req arg of 'self' means this is in a cog and you didnt add it
that is if its a commad, otherwise they need to use get_guild
a separate function
all of this is revolving around us asking your code and you still not giving it and not giving any details
why not pass in ctx if its a func?
works
yes that will work. didnt think of that
Bruhhh no π€¦
That error is coming cz it's not a classmethod but an instance method
or class but dont think so depending on question
or that
how i can call attribute for ! and ? ??
Are there any community standards for packaging plugins for discord?
@commands.command(name="Reset")
@commands.has_any_role("Reset")
async def reset(self,ctx):
await ctx.message.delete()
self.partner.reset_cooldown(ctx)
self.nitropartner.reset_cooldown(ctx)
self.staffpartner.reset_cooldown(ctx)
await ctx.send("Your cooldown has been reset!", delete_after=5)
resetrole = discord.utils.get(ctx.guild.roles, name="Reset")
await ctx.author.remove_roles(resetrole)
how can i turn this command into something where you do -reset @slate swan and it would reset @slate swan 's cooldown?
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the memberβs hash.
str(x) Returns the memberβs name with the discriminator.
first type hint it and then use it as an arg
if reaction.emoji == "β
":
would that work?
and reaction is defined from the wait for
idk whats happening
if str(reaction.emoji) == "β
":
await ctx.reply(f"{ctx.author.display_name}, {user.display_name} agrees to duel with you!")
if str(reaction.emoji) == "β":
await ctx.reply(f"{ctx.author.display_name}, {user.display_name} does not want to duel!")```
thats my code and there is no error
show ur whole code
def ucheck(reaction, user):
return user == user and reaction.message.channel == ctx.channel
a = await ctx.send(f"{user.mention}, do you accept this duel for {amount} :zcoin:?")
await a.add_reaction("β
")
await a.add_reaction("β")
reaction, user = await self.bot.wait_for('reaction_add', timeout = 60, check=ucheck)
if str(reaction.emoji) == "β
":
await ctx.reply(f"{ctx.author.display_name}, {user.display_name} agrees to duel with you!")
if str(reaction.emoji) == "β":
await ctx.reply(f"{ctx.author.display_name}, {user.display_name} does not want to duel!")```
whole code
ok
async def duel(self, ctx, user: discord.Member, amount: int):
users = await self.get_bank_data()
u = ctx.author
def ucheck(reaction, user):
return user == user and reaction.message.channel == ctx.channel
a = await ctx.send(f"{user.mention}, do you accept this duel for {amount} :zcoin:?")
await a.add_reaction("β
")
await a.add_reaction("β")
reaction, user = await self.bot.wait_for('reaction_add', timeout = 60, check=ucheck)
if str(reaction.emoji) == "β
":
await ctx.reply(f"{ctx.author.display_name}, {user.display_name} agrees to duel with you!")
if str(reaction.emoji) == "β":
await ctx.reply(f"{ctx.author.display_name}, {user.display_name} does not want to duel!")```
that good?
ye
k
try changing ur type hint of discord.Member to member
k
it works, thank you!
await ctx.send(f"Click [here]({link}) ")```
why doesnt it work? i want it to be clickable
only works in embed description and field value
k thx
@bot.command()
async def st(ctx, *, user : discord.Member):
message = await ctx.send(user.public_flags)
if 64 in message:
await message.edit('Bravery')```
how am i meant to do this?
public_flags has a value attribute, use that to get the number
so do i use if value is 64: instead
<PublicUserFlags value=64>
thats the output for line 3
ik, im not asking about the output, im asking where did value come from
thats what it says when u use
@bot.command()
async def st(ctx, *, user : discord.Member):
await ctx.send(user.public_flags)```
well for me, considering my flag is bravery
the code does not know where value is, so you need to define it
so 64 = bravery
no
when it comes down to the proper names of things i kinda lose my head lol
thats not supposed to happen
attributes is like one of the basic things you learn first
then how would you not know what that is/means
ive only ever read docs for certain definitives, things like flags and role arguements
otherwise ive developed everything ive ever done off the top of my mind
python itself, i dont know much about, id say at least, but discord.py is really all i do
thats a normal thing for bots, not a big deal
anyways, if you get what i mean, do it, idk how to explain it besides that, i dont want to spoonfeed
_ _
who can help me
def get_prefix(client, message):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
@client.event
async def on_guild_join(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(guild.id)] = 'py.'
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
@client.event
async def on_guild_remove(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes.pop(str(guild.id))
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f)
@client.command()
@commands.has_permision(administrator=True)
async def prefix(ctx, prefix):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(guild.id)] = prefix
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f)
await ctx.send(f'Prefix is now {prefix}!')
its for server prefix in python
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
does anyone know when the discord.py v2.0 is coming out ?
never
Does anyone have documentations/examples on how I can add text to a stored image?
For a welcome message
does anyone know how to link your bot to bloxlink
for a verification command etc.
nvm
Install it to PATH.
any tutorial please?
async def kick(self, ctx , user : discord.Member):
await ctx.guild.kick(user)
if user = None:
await ctx.channel.send("You either didn't mention a user or you can't kick that user.")
else:
await ctx.channel.send(f"Successfully kicked {@<mention.user>} ")
Can I use user = None like that?
no
!code for the love of god.
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Here you go
probably by learning python
Thanks for the helpful answer π
*any language
If what you want is to send a message when user is not given, then just create an error handler and let it send an error message when the error is discord.MissingRequiredArgument.
setting a default value makes more sense to me
Thanks for the one only helpful answer.
Indeed, though it would only handle errors for this command (or any other command that has a default value). Though, it'd be much easier to just do an error handler.
do you even know how to make an error handler
the answer may be helpful, but not if you canβt understand it
I'm reading the docs about it.
oh I get it
error handler for commands.MissingArgument
All I needed was a simple answer. Not step by step what I should write. I could just search in the docs if you just tell me a simple answer
but there are more than one errors
What other error is there?
They will once they check the error handling section in https://github.com/ScopesCodez/disnake-examples haha.
It's still helpful, though. Might be indirect self-promoting. 
Iβm going to be a dick and be super specific to enunciate my point. For starters, ill give you the benefit of the doubt and assume that this is inside of a cog.
ctx.channel.sendisnt needed, you can just doctx.send- once the error occurs, the code will no longer run, therefore your sends are useless.
- you can pass
user=None, but dont - this meansuserwill never equalNone ==not=- you put @< inside the f-string
- you kicked first, checked later
- you dont need a specific error handler, just a try/except. there could be
HTTPException, or many errors
K thanks
@bot.command(name='captcha')
async def verify(ctx):
number_of_strings = 1
length_of_string = 10
for x in range(number_of_strings):
randomstr = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(length_of_string))
confirm = discord.Embed(
title = 'title',
description = 'description',
color = 0xf1c40f
)
confirm.add_field(name='name_1', value='value_1', inline=False)
confirm.add_field(name='name_2', value='value_2')
confirm = await ctx.send(embed=confirm)
await confirm.add_reaction('β
')
await confirm.add_reaction('π«')
i want to the bot wait for the user answer "randomstr" as a reply... how do it?
!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.9)"). 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.9)") 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.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
i did it, but the bot don't answers me
Code?
Lmfao, answered with just 1 letter and 1 word, sucks.
Probably didn't even read the whole thing
i forget, sorry
@bot.command(name='captcha')
async def verify(ctx):
number_of_strings = 1
length_of_string = 10
for x in range(number_of_strings):
randomstr = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(length_of_string))
confirm = discord.Embed(
title = 'title' + ctx.author.name,
description = 'description_1 ``' + randomstr + '``. part_2 description',
color = 0xf1c40f
)
confirm.add_field(name='name_1', value='value_1', inline=False)
confirm.add_field(name='name_2', value='value_2')
def check(message):
return message.content == randomstr and message.channel == ctx.channel
messag = await bot.wait_for("message", check=check)
confirm = await ctx.send(embed=confirm)
await confirm.add_reaction(':white_check_mark:')
await confirm.add_reaction(':no_entry_sign:')```
i forgot, sorry
Does anyone know why when i go to make a new account it says "Bots cannot access this endpoint" even tho it's me?
so this happened to me today, ive never had this problem before, the format i used was !Nitro
\:brainmon:
is how to get an emoji id
alright ty
inside discord
yeah i realized lol i thought it was server id
hello guys one qustion can u guys tell me how like to make my bot like invisbile i want troll my Frineds
wym invisible
like my bot is invisble mode and but my bot works
is that possbile?
status
ohh
ya
.
i don't use them so idk
.
idk
so it cant possbile
!d discord.Status.invisible
The member is βinvisibleβ. In reality, this is only used in sending a presence a la Client.change_presence(). When you receive a userβs presence this will be offline instead.
so whats the code
...
do i click on the link
mhm
everything inside the link is in the embed tho
@commands.Cog.listener()
async def on_member_join(self,member):
em = discord.Embed(title=f'{member.name}',color=discord.Color.random())
em.add_field(name='Account created',value=f"{member.created_at.strftime('%d.%m.%Y, %H:%M Uhr')}")
em.add_field(name='Member joined',value=f"{member.joined_at.strftime('%d.%m.%Y, %H:%M Uhr')}")
em.set_thumbnail(url=f'{member.avatar_url}')
em.set_footer(text=f'{member.id}')
channel = discord.utils.get(client.get_all_channels,name='xxx')
await channel.send(embed=em)
await member.send(f'{member.name},welcome to join our server:{member.guild.name}')
hi , why this is not function?
thats what i had^
when i send it,
is what its meant to be
How can I get users states???
And What intent do I need for it.
Mention me for awnser please. I don't care for ping!
presence
intents = discord.Intents.all()
intents.members = True
just do that\
why not just enable all intents
Is it right
enabled all already
well then you should be fine
Hmm
are intents enabled in your bot via dev portal?
I will try
Yep
yeah you should be fine
send error
when i send it,
is what its meant to be
 is whats in my source
\emoji
thats what i did
but it still sent that output
it has to share a server with the bot
it does
is it animated?
nope
Are you sure that the bot can access the emoji?
its in the server
thats whats in the source
But if the bot can't see the emoji it can't sue it
use*
it can see it
its in the server that the emoji is from
return statment
It can be used inside any python function either an async def or a normal python function
Fixxed. Thanks
https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object-interaction-callback-data-flags is using interaction token to reply to an interaction doesn't count to global rate limit?
All the HTTP methods are under the global rate limit
But buckets can have different rate limits, but they also are limited by the global ratelimit
Funny you said that totally reminded me I should finish implementing components to my wrapper
so it still counts toward the bot's global ratelimit? I thought it uses the webhook's ratelimit (never used one so idk much)
I'm amazed by how you did 99.9% of your wrapper yourself
Coffee addict
haha I like tea more tho
Hmm well you can handle interactions in two ways, over gateway then sending an HTTP call or receiving directly to an HTTP server
I'm pretty sure the gateway one does have a rate limit bucket
It wouldn't make sense for a rate limit on the HTTP server
wait, but I heard that interaction's reply doesn't count towards global one
how to do it over gateway tho?
I'm just going off what the API docs says
It says somewhere every endpoint is under the global rate limit
Your bot receives INTERACTION_CREATE
You parse there
this one?
Uhh
Interaction response does have a bucket though
Interaction id is one of the major parameters iirc
undocumented?
Wait I'm wrong I was thinking about webhook_id
I mean, let me just test this rq anyhow I'll read the response headers
okay
what does [:-3] do in the cog load
Give me a sec for some reason I'm getting a 400
Anyone in here who has worked with the CompontentsBot? (Buttons)
Yea it does have a ratelimit
At least that's what REMAINING: 1 is telling me (that theres 1 more left in the bucket before its depleted)
Oh wait no ignore what I said, I'm completely wrong lmao
I forgot my ratelimiter (the one which I made, and somehow forgot how it works) defaults the remaining requests left to 1 if it isn't found
After reading the full headers I see no X-Ratelimit- headers
so it doesn't have ratelimit headers?
Yea from what I see at least
Hey, anyone shed some light what im doing wrong? Im trying to check if the sentence containts certain words for an automatic reply
if message.content == 'Server'.casefold() or message.content == 'IP'.casefold():
msg = "The IP address is XXXXX"
await message.channel.send(msg)
Sorry for long response I had to manually write the requests for a second
Yes edits have a ratelimit
It seems like 5/5s
@client.command()
@commands.has_permissions(administrator=True)
async def strike(ctx, member: discord.Member, *, reason):
current_strike_count = len(
await bot.strike.find_many_by_custom(
{
"user_id": member.id,
"guild_id": member.guild.id
}
)
) + 1
strike_filter = {"user_id": member.id, "guild_id": member.guild.id}
strike_data = {"reason": reason, "timestamp": ctx.message.created_at, "strike_by": ctx.author.id}
await bot.strike.upsert_custom(strike_filter, strike_data)
embed = discord.Embed(
title="you have been given a strike:",
description=f"__**Reason**__:\n{reason}",
colour=discord.Colour.red(),
timestamp=ctx.message.created_at)
embed.set_author(name=ctx.guild.name, icon_url=ctx.guild.icon_url)
embed.add_feild(name=f"strikes:, value={current_strike_count}", incline=True)
await ctx.send(embed=embed)
no errors given just wont send anything to the discord
if someone can she some light on this that would be great
with interaction tokens also?
Yea I used the token to get the endpoint
I mean, I'm pretty sure you have to use the token to get the correct endpoint
i see thanks
I'm a beginner with Python and been watching videos/exploring the documentation for discord.py. I started using Cogs, but can't figure out what I'm missing to get this dropdown list to display. I think it might be related to the ComponentsBot part, but unsure how that would impact the other code and where I need to designate it. Here is the code for the cog:
from discord.ext import commands
from discord_components import Button, Select, SelectOption, ComponentsBot
class Menu(commands.Cog): # Category type is the class
def init(self, bot): # using self bc using class
self.bot = bot
@commands.command(brief="Provides a menu of all Bot commands")
async def menu(self, ctx):
await ctx.send(content = 'Select an option:', components=[Select(
placeholder='Please select an option.',
Options = [
SelectOption(label='Option 1', value='1'),
SelectOption(label='Option 2', value='2'),
SelectOption(label='Option 3', value='3'),
SelectOption(label='Cancel', value='Cancel'),
],
custom_id='MainMenu'
)])
interaction = await self.bot.wait_for('select_option', check=lambda inter: inter.custom_id == 'MainMenu' and inter.user == ctx.author)
res=interaction.values[0]
if res == 'Cancel':
await interaction.send('You have canceled your select option')
else:
await interaction.send('You have selected %s option' % (res.label))
def setup(bot):
bot.add_cog(Menu(bot))
watching videos or tutorials on discord.py is especially a bad idea
cringe third party libs
yeah, it's been a struggle
yeah, imo most 3rd party libs are pretty bad
slow progress, def have had to hunker down and learn the core of what they arent teaching
discord.py natively have support for buttons and select menus
and buggy
why the 3rd party libs?
i eventually want this to be dynamic, but i need to build the skill for it
i suggest completely drop tutorials and forget what they teach you
the way the code is in here is just kinda eh
open to advice
there are plenty of really good examples in the discord.py examples/view/ subfolder
(i wrote one myself :))
really
the documentation is alright, but not always easy to find what im looking for
yeah the dropdown.py one was my contribution :D
owo cool
yo robin could you look at somthing for me pls
great, best of luck, if you need any more help feel free to come back!
do you have it setup for cogs or is there a better way to do this without it all being one file?
from keep_alive import keep_alive
from discord_components import Button, Select, SelectOption, ComponentsBot
import os
from discord.ext import commands
from settings import *
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!!'))
for filename in os.listdir("./cogs"):
if filename.endswith(".py") and filename != "init.py":
bot.load_extension(f'cogs.{filename[:-3]}')
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}.')
keep_alive()
bot.run(os.getenv('TOKEN'))
'''py
from keep_alive import keep_alive
from discord_components import Button, Select, SelectOption, ComponentsBot
import os
from discord.ext import commands
from settings import *
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!!'))
for filename in os.listdir("./cogs"):
if filename.endswith(".py") and filename != "init.py":
bot.load_extension(f'cogs.{filename[:-3]}')
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}.')
keep_alive()
bot.run(os.getenv('TOKEN'))
'''
backticks, not quotations
hmm, not sure im tracking you
oh
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
it's the key beneath the esc key
sorry, what's the issue?
from keep_alive import keep_alive
from discord_components import Button, Select, SelectOption, ComponentsBot
import os
from discord.ext import commands
from settings import *
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!!'))
for filename in os.listdir("./cogs"):
if filename.endswith(".py") and filename != "__init__.py":
bot.load_extension(f'cogs.{filename[:-3]}')
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}.')
keep_alive()
bot.run(os.getenv('TOKEN'))
thanks
much better
this should work
@commands.has_permissions(administrator=True)
async def strike(ctx, member: discord.Member, *, reason):
current_strike_count = len(
await bot.strike.find_many_by_custom(
{
"user_id": member.id,
"guild_id": member.guild.id
}
)
) + 1
strike_filter = {"user_id": member.id, "guild_id": member.guild.id}
strike_data = {"reason": reason, "timestamp": ctx.message.created_at, "strike_by": ctx.author.id}
await bot.strike.upsert_custom(strike_filter, strike_data)
embed = discord.Embed(
title="you have been given a strike:",
description=f"Reason:\n{reason}",
colour=discord.Colour.red(),
timestamp=ctx.message.created_at)
embed.set_author(name=ctx.guild.name, icon_url=ctx.guild.icon_url)
embed.add_feild(name=f"strikes:, value={current_strike_count}", incline=True)
await ctx.send(embed=embed)```
@blazing coral error?
but again, i would suggest use discord.py's native UI kit, rather than discord_components
it dosnt give an error thats the thing
do you have an error handler?
it just wont work
yes
did you make it yourself though
get rid of it
i'll check your code out and be back
its getting late here so might need to bug you again tomorrow or later this week
thanks again
it's alright, plenty of others here to assist!
so like
eating up all the errors*
yeah that
this thing
yes
mmhm
!code pls
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
yeah hold up forgot to do that
dont send it again
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
embed = discord.Embed(
title='Command Error ',
description=' somthing went wrong ',
colour=discord.Colour.red())
embed.add_field(name=" Missing Reqired Arguments ", value=" Please pas in all requirements for command to work",
inline=True)
await ctx.send(embed=embed)```
just comment it out
why
what do you think your code will do if the error isn't a commands.MissingRequiredArgument?
i.e it doesn't pass the if statement?
using the traceback library is preferable, but for quick testing you can just remove/comment it out
all that dose is tell me like if i didnt type the command in correctly
and ignore everything else
yes
im pretty sure here let me get a pic for you
your code basically says "oh, this error is not commands.MissingRequiredArgument, i'll just ignore it and move on"
which is not what we want whilst troubleshooting
just add an else statement and raise the error there
ah yeah reraising
or do what robin said
this
ok never done an else statement how about would i start that its somthing new
learn more python?
not really
it ignores all other errors completely
which you should never do
errors are extremely important
you could
or comment it out
or reraise the error
or use the traceback library
plenty of options, you choose
i got rid of it
okay, try running it now and see what happens
alright i tried the command and got an error
bruh why are they stacked like that
it's DiscordComponents idk if that relates to this channel in any way
assuming this is discord.py, pass in the approrpate row
ah then i'm not sure, i don't like the 3rd party libraries they're kinda bad imo
yes
its a no attribute error for the word strike
which im confused why
can you post the full traceback?
i tried somthing to see if that worked
i am trying to run my discored bot but i am getting this error -> aiohttp.client_exceptions.ClientConnectorSSLError: Cannot connect to host discord.com:443 ssl:default [[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1091)]
can we see your code?
Hey how do you get a bot to assign roles based on user inputs?
like if you see five words and you use one of the five words to describe yourself it should assign a role
or am I smoking crack?
yeah
you might be connecting to HTTP instead of HTTPS
hey i need help py AttributeError: module 'discord' has no attribute 'Intents'
depends
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\ggmin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\ggmin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\ggmin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord.ext.commands.bot' has no attribute 'strike'
yeah the error speaks for itself
bot.strike is invalid
is bot.strike supposed to be a class?
bot = commands.Bot(command_prefix='+')
bot.remove_command('help')
client = discord.Client()
# more code but i wont show it because it doesnt matter
bot.run(os.environ['DISCORD_TOKEN'])
client.run(os.environ['DISCORD_TOKEN'])
why are you running both a client and a bot?
also i imported discord and stuff
Check a memberβs voice channel ID (if they are in a voice channel tell me the ID) {ping me}
i am using client to change the profile picture
member.voice gives you information about their current voice state
bot can do everything client can do, as bot subclasses client
there is absolutely no need to be using both
oh
ok to make things basic and simple how does the bot.command things work?
wait
bot.command()?
yeah, is that pulling from the discord import?
not necessarily, it's a decorator
if you mean the @bot.command() on top of every function
bot = commands.Bot(command_prefix='+')
bot.remove_command('help')
# more code but i wont show it because it doesnt matter
bot.run(os.environ['DISCORD_TOKEN'])
but it still doesn't work
can you show the imports though?
What are the arguments?
from discord.ext import commands like what commands does this import?
none, it's an attribute
import traceback
import discord, random, asyncio, pickle, os, sys, inspect, datetime, glob
from discord.ext import commands, tasks
from collections import OrderedDict
import copy
So we have to use Member and Self Argumet?
discord.py has 2 extensions
Commands extension - discord.ext.commands
Tasks extension - discord.ext.tasks
i am using other imports for other stuff
not necessarily, if you have the member object, you can just get the .voice attribute
Thanks
I did not know there was a task extension
you'll have to import Intents
discord.Intents in your case
well you need intents right?
if you're doing discord.Intents, you don't have to import intents seperately
it's preferable as you don't flood your namespace
ModuleNotFoundError: No module named 'discord.Intents'
are you doing
import discord.Intents
```?
Putting them in a single list works...
Robin, are you able to send a link to the view folder you mention... I don't find one in the examples directory ... this is where i'm looking at: https://github.com/Rapptz/discord.py/tree/master/examples
the one i wrote is that one
thanks
yes
you just said to import it
all you need is
import discord
then you can do
intents = discord.Intents()
ya but why do i need intents
ok
what does that line of code do?
intents is not used in the program just declared.
@commands.command()
async def move(self, member):
# first_channel = (897862720538419231)
main_channel = member.voice.channel
second_channel = self.client.get_channel(897862929142128650)
member.move_to(second_channel)
member.move_to(main_channel)
why this doesn't work?
Please ping me!
what's the error?
pretty sure move_to needs you to await it
- you're moving them to and back instantaneously
nope still same error aiohttp.client_exceptions.ClientConnectorSSLError: Cannot connect to host discord.com:443 ssl:default [[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1091)]
can you send the full traceback + code?
yeah
Hey @elfin moon!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
are you sure the token is right? and it's being accessed properly?
how do i know that
get rid of the env variables temporarily, and put the token in as plaintext for testing purposes
token is in string format?
yes
it's copy pasted from the discord dev portal?
i see
yes
that's super odd
that's super odd
maybe
umm
@sick birch sorry for lag!
actually i wanna know prefix of my server wit hmy bot commands with discord .py
ctx.prefix
Your using bot right and not client
ok
yes
do you have a custom prefix function? ,Or do you use default one
how to pass the argument that the user wrote to error handler
yes
i haveok
Weird
what?
Like he probably wants to make a bot control panel
Does anyone know that
oauth is only for autentication
you can GET /user/@me/guilds (iirc) to get a guilds
authenticate with the access token
????
/users/@me/guilds gets all the guilds afaik
@sick birch do you know the answer to the question
you can raise exceptions with a custom message
raise someError("some message I want to raise")
so just use your custom prefix function to get the prefix
so I also need to pass an argument to the error handler
Call it with bot and message as args
I don't understand how it will help me if it sends messages
well, the raised error gets propagated to the error handler yes?
that is what you wanted?
no
I want to pass the argument of the commandmember:discord.Member = None in the error handler
like, "Invalid user"?
well, the person writes:
command arg
I need 1arg
well that won't raise any errors
no, like I have an error handler that handles 'membernotfound` and I need it to write 1 argument
so, if the member says invalid user like
command @someuser
and if they don't exist, the error handler says "someuser" doesn't exist?
I didnt expect him to, just was making a point he was lacking more than just some doc knowledge
how do i make my bot delete the message it responded to like
if "Hello" in response.content:
so for example my bot responds "world" and i want it to delete the "hello" that the person sent
hey guys, can someone help me out, wtv method I try to get the member's info, it always returns None, I've tried guild.get_member(id) as well
if ">vcpermit" in message.content and message.author.id in self.mv:
guild = message.guild
c = str(message.content)
d = c.replace(">vcpermit <@!", "")
g = d.replace(">", "")
h = int(g)
m = discord.utils.get(guild.members, id=h)
e = self.mv.index(message.author.id)
f = self.vi[e]
vn = discord.utils.get(guild.channels, id=f)
print(m)
await vn.set_permissions(m, connect=True)
s = "<@" + g + "> has been permitted to your VC!"
await message.channel.send(s)
i want the message my bot responded to be deleted.
Me:Hello (Wants to be auto deleted)
Bot Responds: World
can you share your code?
1min
if "It's " in response.content:
break
intervals = [0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
sleep(random.choice(intervals))
s = response.content.split(" is ")[1].replace(".","")
#response.delete()
print(s)
x = get_mon(s)
#print(options)
print(x)
first_options = x
for i in first_options:
await message.channel.send("It's "+i)
@urban shell
so what do you want to get deleted in this code?
the message that the bot sent?
no the message it responded to
hmm
try something like -
if "It's " in response.content:
await response.delete()
break
yes ty
help\
help
help
!mute 785710193517396008 5d You still haven't improved your behaviour. Unless you can be patient, please don't request help here.
:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1636355431:f> (4 days and 23 hours).
hey I wanted to ask if anyone wanted to collab make some bots with python if so Dm me
This is not really the right place to find developers, there are websites made for that
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
Hi so am trying to make a discord button and so when i click on the button in my server it says This interaction failed
async def button(ctx):
await ctx.message.delete()
await ctx.send(
"This is a button",
components = [
Button(label = 'Click Me!')
]
)
interaction = await client.wait_for("button_click", check=lambda i: i.component.label.startswith("Clicks"))
await interaction.respond(content="Button Clicked")
that's my code
Hi all! please tell me how to use the command on two people, like here:
@lusty swallow
no adding a emoji to a server
!d discord.Guild.create_custom_emoji
await create_custom_emoji(*, name, image, roles=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a custom [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji") for the guild.
There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.
You must have the [`manage_emojis`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_emojis "discord.Permissions.manage_emojis") permission to do this.
Simply create 2 parameters and type hint them to a discord.Member object
oh
Ainβt no body gonna answer me?
thx
idk im not smart
Hi so am trying to make a discord button and so when i click on the button in my server it says This interaction failed
async def button(ctx):
await ctx.message.delete()
await ctx.send(
"This is a button",
components = [
Button(label = 'Click Me!')
]
)
interaction = await client.wait_for("button_click", check=lambda i: i.component.label.startswith("Clicks"))
await interaction.respond(content="Button Clicked")
Yes
Yes
How to make a error command with raises like "Forbidden" and HTTPexception"
Just an example
@bot.command()
async def acoolcommandnamewhichraisesanexception(ctx):
raise discord.Forbidden(...)
raise discord.HTTPException(...)
what should we add in them
the dots
!d discord.Forbidden
exception discord.Forbidden(response, message)```
Exception thatβs raised for when status code 403 occurs.
Subclass of [`HTTPException`](https://discordpy.readthedocs.io/en/master/api.html#discord.HTTPException "discord.HTTPException")
exception discord.HTTPException(response, message)```
Exception thatβs raised when an HTTP request operation fails.
okie
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
Then use the awesome search function
And you see this
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
Well if you don't give an authorization header you won't go far
Try it and see
Reading the Discord's API documentation is helpful
Everything is explained perfectly...
Does anyone know what discord's api link for DMs is
Just like any normal channel
Saying "Didn't work" doesn't help to understand what doesn't work...
No need to send it again you know right?
b'{"message": "404: Not Found", "code": 0}' came and I did https://discord.com/api/v9/channels/@me/someones_id/
No @me needed
saying b'{"message": "405: Method Not Allowed", "code": 0}' now
Well what did you tried to do
requests.post("the url", json=data, headers=header)
What are you trying to do and what is the url
post something in a dm channel
something, a message right?
yes
What is the URL
https://discord.com/api/v9/channels/646303683759439877
Yeah, the docs will help you
well i did say it was a dm channel
o
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
its saying b'{"message": "Unknown Channel", "code": 10003}' now
hello.Why my bot doesnt online after deployed?
Can i find there any devs for discord bot?
maybe
Hey @ornate lichen!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 112, in on_message
async for submission in top:
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncpraw/models/listing/generator.py", line 63, in __anext__
await self._next_batch()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncpraw/models/listing/generator.py", line 73, in _next_batch
self._listing = await self._reddit.get(self.url, params=self.params)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncpraw/reddit.py", line 627, in get
return await self._objectify_request(method="GET", params=params, path=path)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncpraw/reddit.py", line 731, in _objectify_request
await self.request(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncpraw/reddit.py", line 930, in request
return await self._core.request(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncprawcore/sessions.py", line 370, in request
return await self._request_with_retries(```
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncprawcore/sessions.py", line 270, in _request_with_retries
response, saved_exception = await self._make_request(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncprawcore/sessions.py", line 187, in _make_request
response = await self._rate_limiter.call(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncprawcore/rate_limit.py", line 34, in call
kwargs["headers"] = await set_header_callback()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncprawcore/sessions.py", line 322, in _set_header_callback
await self._authorizer.refresh()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncprawcore/auth.py", line 423, in refresh
await self._request_token(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncprawcore/auth.py", line 153, in _request_token
response = await self._authenticator._post(url, **data)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncprawcore/auth.py", line 41, in _post
raise ResponseException(response)
asyncprawcore.exceptions.ResponseException: received 401 HTTP response```
im getting this error
Because you didn't activated the worker in the settings
how to pass the argument that the user wrote to error handler
dont discord.py already do that for you
so, if the member says invalid user like
command @someuser
and if they don't exist, the error handler says "some user" doesn't exist
maybe idk
I have a py cord
yes
?
In nextcord it changes from discord to nextcord that's why I don't like that
At resources there??
π
import nextcord as discord
well yes
please help me for 3 hours I can't decide
Ya that is there but still pycord better
Btw you use nextcord?
help pls
Without code we can't help Β―_(γ)_/Β―
ok ill send it
does ur bot have guilds scope
import asyncpraw
reddit = asyncpraw.Reddit(
client_id=os.getenv("CI"),
client_secret=os.getenv("CS"),
user_agent="lol23",
username="awaffle11",
password=os.getenv("P")
)
@client.event
async def on_message(message):
if message.author==client.user:
return
elif message.content.startswith(">meme"):
subreddit = await reddit.subreddit("memes")
all_subs=[]
top = subreddit.top(limit = 100)
async for submission in top:
all_subs.append(submission)
random_sub =random.choice(all_subs)
name=random_sub.title
url=random_sub.url
em= discord.Embed(title=name)
em.set_image(url=url)
await message.channel.send(embed=em)
this is the code
this is the error
401 is unauthorized. Make sure you're authenticated if you're retrieving data that requires authentication.
how to detect a reaction click
if i wanna import something from my file do i do from utils/utils.py import something? idk how
my directory for the file is \main\utils\utils.py
where main.py is in \main
u cant have / in imports
you also cant have .py in your imports
you can import it using from folder.file import object
folder is your folder name and file is the file name inside the folder
I need to make kick and ban command, but if someone have role i cant kick him. How can I fix this?
what role
hi
So how can I do it
same doubt for me too lol
i guess we have to develop a website of our own
Using Flask
The info I want to show is the number of servers it's invited and the number of people
The problem is I don't know flask
i used task.loop function to check my databse and says whether anyone had birthday today.
But when i task.loop function some other commands are not working.
Can someone help me how to fix this?\
mongodb
Pymongo or motor?
pymongo
Is motor has same syntax as mongodb?
oh ty
how can I get the amount of messages that are being sent every second? my current code:
def messages_per_second():
differences = []
counter = 0
current_time = 0
for cached_message in client.cached_messages:
sent_time = cached_message.created_at.timestamp()
if sent_time - current_time > 1:
differences.append(counter)
current_time = sent_time
counter = 0
else:
counter += 1
average = round(sum(differences)/len(differences), 2)
return average
i dont feel like this is correct tho
how to make a message that only the one who called the command sees
u cant unless u use interactions
it's like
slash commands
and they are in py-cord
im not sure if interactions are supported in discord.py but in disnake its ```py
@client.slash_command(name="ping", description="Pong")
async def ping_command(interaction):
await interaction.response.send_message("Pong", ephemeral=True)
disnake is better than py-cord?
and will you be able to throw off the option for cog
how to use them in cog
Well, u can say so, since it's the first fork which got context menus and slash commands among all other forks haha
maybe
@commands.slash_command() in cogs
ok
How to detect a reaction on a message
!d discord.on_reaction_add
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesnβt require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message itβs required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
what should i do
I want a message to be send when a reaction is detected on a message
this
oh hmm i thought that was for adding reaction
how to get a command message
Well it is
For reaction removal,
!d discord.on_reaction_remove
discord.on_reaction_remove(reaction, user)```
Called when a message has a reaction removed from it. Similar to on\_message\_edit, if the message is not found in the internal message cache, then this event will not be called.
Note
To get the message being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires both [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") and [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
Note
Consider using [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") if you need this and do not want to enable the members intent.
so im making a bot with Component with the discord_components libirary
My problem is that the Componentctx object returns None when asking for message attribute although in the docs it says that there is a message attribute for Componentctx type
Ohh i get it so it should both be the same?
Well, think a little bit. If you have a string that is Click me and you check if the string starts with Clicks, do you think it will find it?
Are you saying that i should learn more on python?
Because yeah maybe videos dont really look the same as you do it in your own code if that make sense
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Ok
I got a question
Can python bots create a staff application where ppl would answer a bunch/some questions and then the answers would get send to you for review
And then it sends a dm to either that u got accepted or denied and for whatever results it states your reason
import discord
from discord.ext import commands
import time
# -------------------- Cogs --------------------
class movespam(commands.Cog):
def __init__(self, client):
self.client = client
# -------------------- Launch --------------------
@commands.Cog.listener()
async def on_ready(self):
print('Loaded Move Spam')
def is_it_me(ctx):
return ctx.author.id == 850727380220772415
# -------------------- Spam Moves --------------------
@commands.command()
@commands.check(is_it_me)
async def move(self, member):
main_channel = self.client.get_channel(879332800656986152)
second_channel = self.client.get_channel(897862929142128650)
await member.move_to(second_channel)
time.sleep(1)
await member.move_to(main_channel)
# -------------------- Cogs Setup --------------------
def setup(client):
client.add_cog(movespam(client))
# -------------------- Comment --------------------
Why this isn't working? I get no errors
Which are?
@client.event
async def on_message(message):
if message.content.startswith('$thumb'):
channel = message.channel
await channel.send('Send me that thumbsup reaction, mate')
def check(reaction, user):
return user == message.author and str(reaction.emoji) == 'thumbsup'
try:
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await channel.send('thumbsdown')
else:
await channel.send('thumbsup')
here's an example
What's member?
Don't use time.sleep use asyncio.sleep
And if you want to spam move the user, you might want to make a loop
Idek what he's trying to do
ok I want to do ?move @slate swan It should move me to 2 channels
member : discord.Member?
Ye
import discord
from discord.ext import commands
import time
# -------------------- Cogs --------------------
class movespam(commands.Cog):
def __init__(self, client):
self.client = client
# -------------------- Launch --------------------
@commands.Cog.listener()
async def on_ready(self):
print('Loaded Move Spam')
def is_it_me(ctx):
return ctx.author.id == 850727380220772415
# -------------------- Spam Moves --------------------
@commands.command()
@commands.check(is_it_me)
async def move(self, member : discord.Member):
main_channel = self.client.get_channel(879332800656986152)
second_channel = self.client.get_channel(897862929142128650)
await member.move_to(second_channel)
time.sleep(1)
await member.move_to(main_channel)
# -------------------- Cogs Setup --------------------
def setup(client):
client.add_cog(movespam(client))
# -------------------- Comment --------------------
Still doesn't work man
error?
how to use 'inter.response` in error handler
nothing
does the cog not load?
also , dont use time.sleep in async code
import asyncio
await asyncio.sleep(time)``` use this
?
using the wait_for methods are you talking about?
you only have ctx in an error handler
@bot.command(name='captcha')
async def verify(ctx):
number_of_strings = 1
length_of_string = 10
for x in range(number_of_strings):
randomstr = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(length_of_string))
confirm = discord.Embed(
title = 'title ' + ctx.author.name,
description = 'part_1: ``' + randomstr + '``. part_2',
color = 0xf1c40f
)
confirm.add_field(name='name_1', value='value_1', inline=False)
confirm.add_field(name='name_2', value='value_2')
member = ctx.author
confirm = await ctx.send(embed=confirm)
def check(message, user):
return user == ctx.message.author and message.channel == ctx.message.channel and user != user.bot
await bot.wait_for("message", check=check)
await bot.add_roles(member, role)
I want to the bot get the answer (in case, the randomstr) and then check if this answer is correct but my code are wrong and i don't know what
use try and except wherever you use the button responses
except lmao
autocorrect , something likely to happen on an android device
you dont have a context object in your command
still nothing
show your current code
Can someone help me?
AttributeError: type object '_asyncio.Task' has no attribute 'current_task'
what is this error?
issue with this import from discord.ext import tasks
the whole code works fine on repl it but not on my local pc
ohh nvm I was using python 3.9
o
1 package isnt supported on 3.9
thanks for the help
π
how do I use 3.8 along with 3.9
not sure
hmm
U can use only one version at one time
so im making a bot with Component with the discord_components libirary
My problem is that the Componentctx object returns None when asking for message attribute although in the docs it says that there is a message attribute for Componentctx type
The name of the command.
use that to check if its a certain command
Why not just use the humanize module instead of doing math?
!pypi humanize
^ Converts literally anything into seconds, minutes, hours, days, weeks or even years
what bad here?
@client.event
async def on_member_remove(member):
channel = client.get_channel(902965184044335155)
embed=discord.Embed(title=f"Ε»egnaj {member.name}...", description=f"Ε»egnaj, mamy nadzieje ΕΌe kiedyΕ wrΓ³cisz jeszcze na nasz serwer!", colour=discord.Colour.red)
embed.set_thumbnail(url=member.avatar_url)
await channel.send(embed=embed)
try discord.Color.red()
and not discord.Color.red
what is the official way for making buttons
color=discord.Color.red() put brackets @rotund nova
ok
What lib you using prefer pycord ezzy in it
just add () after.red
Yes
hm im using un official
Oof
we have add another )
Use pycord instead
ok
what
add 2 )) idk it depends
Always first delete discord.py then install whatever lib you want
yes add another one of ) too
or error
thats why i said add
...nvm i cant explain its my fault
@final shard
ok
thx
activity = discord.Game(name="McForever.eu - Najlepszy serwer minecraft.", type=2)
await client.change_presence(status=discord.Status.idle, activity=activity)
``` can i change it to status online?
Bruh no
What is the error??
dont error i just want online but idk how
Ohh
Lol just change the type=1
ok
Try that
thx
Or else it could be 0 i am not sure
Cuz i use different statement for status
@rotund nova it worked?
Please just let the helper always know @rotund nova whenver you ask ok?
If it works or not
What youβre trying to help with here is literally impossible
Lol exactly
Literally jus get rid of the status part then
XDDD
It will default the status to online
Quick question, which data base would be the best to start of with for bots?
Alright, thanks.
Hmmm ofc ig he is kinda a rewrite lol
no working
delete activity=activity?
No
No
Lol
I said status
how to make a command that will give a link to a video on YouTube
Wait yes
You did discord.Status.idle
await client.change_presence(activity=activity)
So do online
?
Yes
bro I literally said delete it because it will default onto online. Why pass in unnecessary arguments
Wait bettrr i will trll @rotund nova a better method
working
that
isn't that how you use functions though
A command which will just send a youtube link message?
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.Game, name="your status"```
yes by the name in the argument
Take a look at your his intentions
@rotund nova
@client.command(name='link')
async def youtube(ctx):
print(ctx.author.name)
await ctx.send("link")
```?
hm
Do not change status in an on_ready event
use the bot constructor itself to do that
Bruh what even is that
Link would undefined unless itβs in some outer scope
Hello. If I make a dashboard for my bot will people be able to see it on Google
The invite link
And youβre missing a terminating double quote
Depends if you make it a public website.
Hi guys. I am getting this error in this line
try:
reaction , user = await client.wait_for("reaction_add", check = lambda reaction,user: user == ctx.author and
reaction.emoji in buttons and reaction.message.id == msg.id, timeout = 40)
Error:
AttributeError: module 'discord.client' has no attribute 'wait_for'
It was working fine in 'main.py' but started to give this error when I re-wrote it in a cog.
Hey i need free host my bot. How can i do it?
thereβs multiple ways
U can use repl.it or heroku
I made it in pycharm
π₯² . Gladly yes
Whatβs used often are vps's(or dedis), rasp pi, some people use old laptops as well
I host mine in heroku. Its fine. no problems, not that great either.
.
- Bots are not what the platform is designed for. Heroku is designed to provide web servers (like Django, Flask, etc). This is why they give you a domain name and open a port on their local emulator.
- Heroku's environment is heavily containerized, making it significantly underpowered for a standard use case.
- Heroku's environment is volatile. In order to handle the insane amount of users trying to use it for their own applications, Heroku will dispose your environment every time your application dies unless you pay.
- Heroku has minimal system dependency control. If any of your Python requirements need C bindings (such as PyNaCl binding to libsodium, or lxml binding to libxml), they are unlikely to function properly, if at all, in a native environment. As such, you often need to resort to adding third-party buildpacks to facilitate otherwise normal CPython extension functionality. (This is the reason why voice doesn't work natively on heroku.)
- Heroku only offers a limited amount of time on their free programme for your applications. If you exceed this limit, which you probably will, they'll shut down your application until your free credit resets.
Show me where your client variable is defined
client = commands.Bot(command_prefix='oi ')
in main.py
What about in your cog
Oh, is that snippet of code you have in your main?
yes
do i need to import discord-interactions for slash commands=?
Thatβs interesting. Bot does have a .wait_for() method
The modmail
discord.client that's the module, not the class
check your imports
hello
@client.command()
@commands.has_permission(administrator=true)
async def hello world(ctx):
await ctx.send(f"hello {ctx.author.mention})
this is not works

