#discord-bots
1 messages · Page 500 of 1
!d discord.VoiceState.self_video
Indicates if the user is currently broadcasting video.
?
It's from the voicestate class
can you send the docs?
he just did
Click the blue link in the embed
click on link
oh sorry, i didnt notice it
hm, it works for me
it works for me in dms too, i did get a 403 Forbidden error on reaction_remove tho, it works normally in a guild
cool
The bot can't remove user reactions in dms
ohh
You can remove only the bot's reactions
Bots don't have reaction perms in DMs.
i saw tht now 😦
I have a looped function that used to be in main but I've moved it to a Cog file for organization. I used to func.start() in main as well.
async def startup_code():
func.start()
# Other stuff
bot.loop.create_task(startup_code())
bot.run(token)
I'm wondering how I should start func now that it's in a cog file.
You could just import the cog
from cogs import cog_file_name
async def startup_code():
cog_file_name.func.start()
# Other stuff
bot.loop.create_task(startup_code())
bot.run(token)
Do you mean like this?
more like ```py
from cogs.cog_file_name import func_name
hoping this guy doesn't for loop his dir to load the cogs
I meant that they cant remove reactions..
If I did that, startup_code would like like
async def startup_code():
func.start()
# Other stuff
right?
I dunno i don't know your code
What happened?
initial_extensions = [f"cogs.{f[:-3]}" for f in os.listdir("cogs") if os.path.isfile(os.path.join("cogs", f))]
# Load the cogs
if __name__ == '__main__':
for extension in initial_extensions:
bot.load_extension(extension)
Why not?
panic
Is there something wrong with this?
I don't think so
I am getting Nonetype error when I use the docs code for dming. Help! https://discordpy.readthedocs.io/en/latest/faq.html#how-do-i-send-a-dm
Some think it's great but i think it's not so great, imo there are more cons than pros
What are the cons and what are the pros?
Show the full error.
- 'NoneType' object has no attribute 'send'```
Show the full error.
that is what I got.
Can I see your code?
Personally if you use any kind of __*__ file you can't use this method, yes i tried to exclude it in the code. All cogs have to be in one place unless you want to join other dirs. And it's just pretty unclear for others what is happening.
As for pros it's easy for beginners, for many cogs you don't have to type the path.
What IDE are you using?
Seems like member is returning None
Cz of a wrong ID or the member not being in the cache (if they using get_member)
replit (ik it is bad)
@karmic totem can I see your code?
It's much harder to figure out what's wrong without the full error message.
ok I'll remove the except for a few seconds
Ended up trying this
from cogs.cog_file_name import CogClassName
async def startup_code():
CogClassName.func.start()
# Other stuff
The fact that it doesn't show the full error message is the biggest red flag to me.
Does the cog folder have an init?
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 42, in on_message
await user.send(message.content.split[2])
AttributeError: 'NoneType' object has no attribute 'send'```
Yea, user is None
line 42 user is ded
The cog folder does not have an __init__.py file if that's what you're asking.
Can I see your code, for the 4th time?
Yeah that's why you cannot import files from that dir returning to my cons/pros list -> #discord-bots message
if message.channel.id == 891991473925541928:
if message.content.startswith('-dmto '):
try:
us = message.content.split(' ')[1]
user = client.get_user(int(us))
await user.send(message.content.split[2])
except Exception as e:
await message.reply(e)```
class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the decorator or functional interface.
My idea, #discord-bots message, ended up not working for a different reason.
Traceback (most recent call last):
File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\tasks\__init__.py", line 101, in _loop
await self.coro(*args, **kwargs)
TypeError: water_check_scheduler() missing 1 required positional argument: 'self'
Because if a function is inside a class you need to have self in the function constructor.
Ik. but if I am using my code...
Try printing us
ok
The function inside a class does have self in the function constructor. I think the problem is that I used the cog name instead of an instance of the class when I did
WaterCheck.water_check_scheduler.start()
in startup_code.
Therefore there was no self passed to the method.
same error
If I have an error handler and I have a command error for a specific command how do I stop it from sending both of the errors if an error got raised?
I could do something like
from cogs.cog_file_name import CogClassName
async def startup_code():
CogClassName(bot).func.start()
# Other stuff
but this seems weird and probably wrong. It feels weird because I am creating an instance of the class just for one function. Normally, when you import stuff, you can just use the function. However, since this function is part of a class, I need to use the class to call the function. And since the function needs self, it seems like I have to use an instance of the class instead of the class itself.
Ik... What did it print?
!d discord.ext.commands.Command.has_error_handler use this in the global error handler
has_error_handler()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)"): Checks whether the command has an error handler registered.
New in version 1.7.
make the function as a staticmethod if you're not using the instance in the function
remove () at your bot event decorator, it's not callable
I think that I am using the instance in the function.
It's like this
class CogName(commands.Cog):
def __init__(self, bot):
self.bot = bot
@tasks.loop(count=1)
async def looped_function__scheduler(self):
# Do some stuff
self.looped_function.start()
@tasks.loop(hours=1)
async def looped_function(self):
# Do some stuff
guild = discord.utils.get(self.bot.guilds, name=GUILD_NAME)
If I could get around referencing self in looped_function, I could also avoid using self in looped_function_scheduler. If I could do that, then I think that I could make looped_function_scheduler into a static method.
So now my question becomes: Is it possible to get the guild object in looped_function without using self.bot?
And bot.process_commands() must be used at the end of the event
hm @commands.has_error_handler() then?
What I wanted: py us = uss.split(' | ') print(f'{us[0]} - {us[1]}') ... 123345567543 - Hello
plz help me
You need the Command object
ctx.command.has_error_handler()
hm
if this is specifically cog class, you can get the instance from bot.get_cog instead
stella greek name
omg
Indents
yes
im from greece
what should i do
that's cool, but kinda off topic
the indentations
Yes, this is specifically a cog class. Why would we use bot.get_cog?
i dont know good coding can you help me pls ?
because that's the original instance you made, why would you need to create one just to call 1 method, what if you have another variable that is attached to that instance
and tbh that's literally the point of an instance
So you're saying that when I start the looped function in main, I could do
bot.get_cog("CogClassName").looped_function_scheduler.start()
?
sure, but why start there, why not just in the init or something
Like start the looped_function_scheduler in the __init__ of CogClassName?
yes
I didn't think of that.
that way you can stop them during unloading the cog so you dont duplicate the task
and where would I put this exactly?
In your global error handler
I don't unload cogs for what it's worth.
When you make a global error handler you have ctx and the error as the params
So you can just do ctx.command to return the Command that raised the error
sure, but just in case, the feature is there, what if something went wrong, so you simply just unload the extension, and there goes the task, it's your choice though
How should I go about saving all the messages from a channel in my private server (including messages in public/private threads) into a JSON file?
@slate swan I'm confused about how to start the looped_function in the looped_function_scheduler. Am I supposed to make both the scheduler and the looped function into staticmethods? When I try to start the looped_function in the looped_function_schedluler, it says that looped_function isn't defined.
Also, this doesn't solve the problem of using self in looped_function since I still need to get the guild. Perhaps though I could pass bot to the scheduler and then have the scheduler pass bot to the looped function. What do you think about this idea?
what's wrong with just doing ```py
class CogClass(commands.Cog):
def init(self, bot):
self.your_task.start()
@tasks.loop()
async def your_task(self):
...
Hey is it possible to do this? I just want to change the color of the Embed and nothing else.
await slotbed.edit(color=discord.Color.green())
set it at the Embed object, and pass the embed object into the message edit
You mean I have to make a copy of the Embed that is green instead and change the Embed to that copy?
this is not possible
you dont have to make a copy of it, just use the original embed you had, set the color attribute, and pass it to the message.edit
make a clone of the same embed and just change the color
make a function for embeds
or some thing different
Well that was what I was thinking about but that wont work. In the Embed I got a 3 random symbols that changes, if I copy the same Embed it wont be the same symbols as it was before
I could take your idea and start the scheduler like this
class CogClass(commands.Cog):
def __init__(self, bot):
self.my_task_scheduler.start()
@tasks.loop(hours=1)
async def my_task():
...
# Need to reference bot in here
@tasks.loop(count=1)
async def my_task_scheduler(self):
...
# Start my_task
The problem with this is that it appears as though my_task is not defined when I reference it in my_task_scheduler.
just reference them with self? your method there isn't even static, and even if it's static, you still need the class/instance to reference it
what kinda symbols?
Or it is Emojis, like hearts in different colors and so
mate make a function for embeds which u want only the color to change
Ah yea
Are you talking about this?
class CogClass(commands.Cog):
def __init__(self, bot):
self.my_task_scheduler.start()
@tasks.loop(hours=1)
async def my_task():
...
# Need to reference bot in here
@staticmethod
@tasks.loop(count=1)
async def my_task_scheduler(self):
...
self.my_task.start()
why staticmethod?
i suggest reading on how to actually use a staticmethod, anyways, since you already have the instance reference, you dont have to make the method a staticmethod, remove that
async def my_embeds(color):
embed=discord.Embed(title="hmm", description="",color=color)
return embed
#....somewhere in code.....
my_em=await my_embeds(color=somecolor)
await ctx.send(embed=my_em)```
@surreal sierra
this might work
why not just set the color attribute of the original embed like i originally suggested
hmm we can go to shop by front door and also through back door
I thought that I was supposed to use staticmethod for the scheduler because the scheduler doesn't really need the instance of the class. The only reason I thought that it did need the instance of the class was because I didn't know how to reference looped_function without it.
i suggested that, because you needed it outside the class, since now you're using it inside the class, there isn't a reason for it
okay thanks!
where did you define looped_function exactly?
Oh okay. I misunderstood the importance of that.
yea, i mean it's called overhead for a reason
So I should be able to do this.
class CogClass(commands.Cog):
def __init__(self, bot):
self.my_task_scheduler.start()
@tasks.loop(hours=1)
async def my_task(self):
...
@tasks.loop(count=1)
async def my_task_scheduler(self):
...
self.my_task.start()
Hello, I'm trying to make command where I can create embed with commands. This is my code:
@client.command()
async def emek(ctx):
def check(message):
return message.author == ctx.author and message.channel == ctx.channel
await ctx.send('Waiting for a title')
title = await client.wait_for('message', check=check)
await ctx.send('Waiting for a description')
desc = await client.wait_for('message', check=check)
await ctx.send('Channel ID')
guild = client.get_guild(12345678)
int((await client.wait_for('message', check=check)).content)
channel_id = await client.wait_for('message', check=check)
channel = guild.get_channel(int(channel_id.content))
embed = discord.Embed(title=title.content, description=desc.content, color=discord.Color.blue())
await channel.send(embed=embed)```
I do not get any error but when I send the channel id, nothing happens. What should I do?
but with my method you can even change internal descriptions in that function so you can reuse the code
now here's another issue, why do you have a task, that calls another task
which is kinda pointless cause you can do that by just embed.description = "new description", it was made editable since Embeds are pretty much over glorified json handler
Good question. I wanted a way to get the task on a certain schedule. For all intents and purposes, the scheduler is just a helper function for the looped task.
alright
my_embed=discord.Embed(title="Ur Title", description="Content of ur Embed")
await ctx.send(embed=my_embed)```
that's not a normal embed
please, read my code again and if you know what should i do, i will be really happy to see
You are not taking any arguments in the command
Like embed title, description
etc
Whatever you need to make your embed
i want when i type .emek to send Waiting for a title, then i need to type a title for the embed, the bot checks it then sendsWaiting for a description, then checks again and sends Channel ID, where i need to answer with the channel id, where i want my embed to be sent
they are using wait_for for that lol
so what should i do then? :/
No no It's okay, i didn’t notice the wait_for part
np, but what should i do
so the bot sends the embed in this channel
do u send the embed to some other channel?
yes
probably a silenced error, do you have an error handler
i'm not sure, i think yes
anyone knows tag prefix?
it's an old bot, prob before a year 1k lines bot lol
@slate swanCan you think of a way get a looped task on a schedule in the task itself?
wdym lol, just do what you just did
btw u can also use
sendhere=client.get_channel(int(value))
await sendhere.send(embed=someembed)```
try disabling the error handler first, and see if it raises any error
Well you asked why I was using a task to call a task. This made me wonder if there was something wrong with doing it that way.
this is for sending in the exact channel i am, i want in channel i say
just pass the channel id there
few ways to be honest to do it, you could use task.before_loop, use loop.create_task for a 1 time task call
i don't have error handler
I see
in your code here, ```py
int((await client.wait_for('message', check=check)).content)
channel_id = await client.wait_for('message', check=check)
you're doing wait_for twice, so perhaps when you sent the first channel id, it went to your int there, hence there isn't a reply or an error
probably you send it twice it will
so i need to delete the int.... thing?
yea, since you're not using it
okay
I like the before_loop idea a lot. Thank you.
will try
This is what i got after removing the line
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'get_channel'
where i place the id of the channel, the bot prints this
Hey! I want my embed to have fields like this:
Field 1 Field 2
Descr 1 Descr 2
Field 3 Field 4
Descr 3 Descr 4
But when I add inline=False to 3rd field, the 4th field goes to third line like this:
Field 1 Field 2
Descr 1 Descr 2
Field 3
Descr 3
Field 4
Descr 4
How can I fix that?
do it in the seconds i think
that's how inline =False work
it means your guild is None, so your bot.get_guild is returning none meaning id isn't valid, or isn't cached in your bot
the id is valid
If I do it in second then second will do to second line
what should i do?
I can't fix that?
probably isn't cached, but im too lazy to know, so you could instead just use bot.get_channel, avoiding needing a guild
you cannot do like that
2
2
there should be a way of doing this , let me check
@slate swan it worked, TYSM !!!!! ❤️ ❤️ ❤️
na doing this wont make you able to set it a 2x2, usually people just make the third field as no character to hide it
thx
but this looks horrible in mobile
oh,
yea embeds in mobile looks horrible anyways
yea
You can do that:
two fields inline=True
one field inline=False (use invisible characters here)
two fields inline=True
hello, Can someone help me, chat by private plis
why not just ask here, or in a help channel for less traffic #❓|how-to-get-help
@client.command()
async def userinfo(ctx, member: discord.Member = None):
member = ctx.author if not member else member
roles = [role for role in member.roles]
embed = discord.Embed(
color = member.color,
timestamp = ctx.messages.created_at
)
embed.set_author(name=f"User Info - {member}")
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.avatar_url)
embed.add_field(name="ID:", value=member.id)
embed.add_field(name="Guild Name:", value=member.display_name)
embed.add_field(name="Created At:", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"))
embed.add_field(name="Joined At:", value=member.joined_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"))
embed.add_field(name=f"Roles ({len(roles)})", value=" ".join([role.mention for role in roles]))
embed.add_field(name="Top Role:", value=member.top_role.mention)
embed.add_field(name="Is Bot", value=member.bot)
await ctx.send(embed=embed)
why it doesn't send the message?
How do I send a message to a certain channel? Like I do a command like ??ga <Whatever> I want to send the <Whatever> part to a particular channel
@reef shell Do you know why? it is not shows any error.
how do i get my bot to wait, say, 5 seconds, before replying to the command?
btw
await asyncio.sleep(5)
k
Umm...
@bot.command()
async def ga(ctx, *, arg):
if ctx.channel.id == 886837547328761868:
await ctx.channel_send
await ctx.send(arg)
``` What I've done is made the command channel specific. Now how do I make it send the `arg` to another channel. Do I create an arg like gachannel == 7875456789
timestamp = ctx.message.created_at
(I also want to send a copy to the channel the command was made. so thats why there is the last line)
or making it like this:
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
msg = '**Still on cooldown**, please try again in {:.2f}s'.format(
error.retry_after)
await ctx.send(msg, delete_after=6)
then use this in a command:
@commands.cooldown(1, 60, commands.BucketType.user)
u can change it any time.
also which dpy version are you using
Me?
can we check a phrase in a role name?
like if "admin" in member.roles or something
no sorry, lucus
Ohh
Can you help me??
like make a command only work if you have a role?
ga(ctx, channel : discord.TextChannel, *, arg)
if this is the code, whats wrong with it? im getting an error
no like getting a list of members having roles which has a specific word in the role name
IDK sorry
do i need to like enable it or smth?
what error?
it must be in a separate line lol
....
I don't need them to choose. I just need to edit the line to where I want to send
like i want the output sent to a particular channel
it works, thx
the particular channel doesnt change. I choose it once and thats where i want it to go
then just don't take channel arg and then get that particuler channel using bot.get_channel(channel_id) and then send
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").
These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
@bot.command()
async def ga(ctx, *, arg):
channel = bot.get_channel(886837532854198272)
if ctx.channel.id == 886837547328761868:
await ctx.channel.send(arg)
Is this good?
yeah, but it's better ga(ctx, *, arg : str)
ok
@reef shell I have a querstion..
guild_ids = [i dont wanna pubish myserver ID]
@slash.slash(
name="userinfo",
description="Shows a user-info.",
guild_ids = guild_ids
)
async def userinfo(ctx, member: discord.Member = None):
member = ctx.author if not member else member
roles = [role for role in member.roles]
embed = discord.Embed(
color = member.color,
timestamp = ctx.message.created_at
)
embed.set_author(name=f"User Info - {member}")
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.avatar_url)
embed.add_field(name="ID:", value=member.id, inline=False)
embed.add_field(name="Guild Name:", value=member.display_name, inline=False)
embed.add_field(name="Created At:", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"), inline=False)
embed.add_field(name="Joined At:", value=member.joined_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"), inline=False)
embed.add_field(name=f"Roles ({len(roles)})", value=" ".join([role.mention for role in roles]), inline=False)
embed.add_field(name="Top Role:", value=member.top_role.mention, inline=False)
embed.add_field(name="Is Bot", value=member.bot, inline=False)
await ctx.send(embed=embed)
Why it is wrote: the interaction failed???
Quick question: How do I put the content of the arg in "between here" ??
wdym
Currently the output of this code will be whatever was after ??ga
@bot.command()
async def ga(ctx, *, arg : str):
channel = bot.get_channel(886837532854198272)
if ctx.channel.id == 886837547328761868:
await channel.send(arg)
await ctx.send (arg)
``` I want to place it between ""
you can do {arg!r} and make the string an fstring
then do .ga "hi"
!e ```py
arg = '123'
print(f'{arg!r}')
@hasty iron :white_check_mark: Your eval job has completed with return code 0.
'123'
!e
arg = 1234
print(f"{arg!r}")
@heavy radish :white_check_mark: Your eval job has completed with return code 0.
1234
!e
arg = 1234
print(f"'{arg!r}'")
@heavy radish :white_check_mark: Your eval job has completed with return code 0.
'1234'
Hm
!e
arg = 1234
print('f"{arg!r}"')
@heavy radish :white_check_mark: Your eval job has completed with return code 0.
f"{arg!r}"
???
@commands.command()
async def listadmins(self, ctx):
roleslist = ctx.guild.roles
for role in roleslist:
if "developer" in role.name:
await ctx.send(role.name)```
its not working, what am i doing wrong?
guys how can i create log bot ?
on_bann
on_message_update
on_user_profile_update
like this
well nothing is wrong with your code
it must be that there isnt a role that contains "developer" in its name
if "developer".lower() in role.name: this is correct , right?
"developer" is already lower case though
yes ik
well i have a role Developer & Creater , doing "Developer".lower() in role.name: should get me that role name right?
you'd do "developer" in role.name.lower()
ye that thanks
my friend is wanting me to add a credit/rpg system to the bot im making for our discord server, could someone walk me through that one-on-one by any chance? I'm not gonna be online for much longer but will be on this evening
ctx.author.name} whats the one to get their name and tag? but not mention
only the name
str(ctx.author)
to get both name and tag just use ctx.author
ok
if you're willing to help me with this, pls ping me and I'll get back to you later
what rpg/ ?
what do you mean?
i dont understand the question
"what is an rpg bot?"
"what do you mean /rpg?"
what do you mean
i also dont understand wdym by credits/rpg
the way he put it he wants a "credit system" where you can use daily/work/etc. to gain bot currency
how can we help with that?
i have no idea how to set that up, never done anything like it before
i have a friend who could help me but is not responding to my messages rn
hasnt for like a day now
how can i get members with a role having Admin in their roles name?
guys, any idea on how i would make a flask app that can get a discord.py bots data in a seperate app? i guess some kind of discord api
You have to put options for the slash commands
you can use IPC
does that host my bot along with a flask application?
or like get the bots data from it
ipc is inter-process communication, it doesn’t host anything
how do make it so that a command requires the user to have a certain permission to use?
check if the author has that permission if they have it then do the command
can u give me an example of how to put that in the code?
discord.ext.commands.Bot.has_guild_permissions @commands.has_guild_permissions(kick_members=True)
that's a decorator so you can put it where your command decorator is
k
Can anyone please help me?
I am trying to create a bot that needs to read the message and from the message take the email and send it the amount written through coinbase
sounds like a cool task
@ client.command(pass_context=True) async def number(ctx, z): y = randrange(100) await ctx.send('Guess the number!') while True: if y == int(z): await ctx.send("Congrats!") break await ctx.send("smaller" if (y < z) else "Bigger")
raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: '<' not supported between instances of 'int' and 'str'
pass_context is deprecated
Yes but I'm getting involved with it
typehint z to int
not sure I understand
that won't change anything. the issue is await ctx.send("smaller" if (y < z) else "Bigger"), it should be await ctx.send("smaller" if (y < int(z)) else "Bigger")
in normal python it wont, in dpy it will
ah yeah i guess, either use the typehint and remove all of the int conversions or convert them both manually
dpy converts the __annotations__ in your function to the type you expect
Thank you!
It works
works as well!
Thank you!

This was fast and useful! Great community.
I need this code
import json, hmac, hashlib, time, requests
from requests.auth import AuthBase
# Before implementation, set environmental variables with the names API_KEY and API_SECRET
API_KEY = 'API_KEY'
API_SECRET = 'API_SECRET'
# Create custom authentication for Coinbase API
class CoinbaseWalletAuth(AuthBase):
def __init__(self, api_key, secret_key):
self.api_key = api_key
self.secret_key = secret_key
def __call__(self, request):
timestamp = str(int(time.time()))
message = timestamp + request.method + request.path_url + (request.body or '')
signature = hmac.new(self.secret_key, message, hashlib.sha256).hexdigest()
request.headers.update({
'CB-ACCESS-SIGN': signature,
'CB-ACCESS-TIMESTAMP': timestamp,
'CB-ACCESS-KEY': self.api_key,
})
return request
api_url = 'https://api.coinbase.com/v2/'
auth = CoinbaseWalletAuth(API_KEY, API_SECRET)
# Get current user
r = requests.get(api_url + 'user', auth=auth)
print r.json()
# {u'data': {u'username': None, u'resource': u'user', u'name': u'User'...
# Send funds
tx = {
'type': 'send',
'to': 'user@example.com',
'amount': '10.0',
'currency': 'USD',
}
r = requests.post(api_url + 'accounts/primary/transactions', json=tx, auth=auth)
print r.json()
# {u'data': {u'status': u'pending', u'amount': {u'currency': u'BTC'...
this is from coinbase developer web
How do I get
API_KEY and API_SECRET ?
@broken dirge
I'm sorry but I'm new to python
import discord
import os
import music
my_secret = os.environ['TOKEN']
client = discord.Client()
cogs = [music]
client = commands.Bot(command_prefix='!', intents = discord.Intents.all())
for i in range(len(cogs)):
cogs[i].setup()
file "main.py", line 4, in <module>
import music
oh ok thx
I use Coinbase though
u need an api key?
so it's interesting for me as well
yes
Hello guys I have a favor, is here someone who is master doing discord bots and something with blockchain etc...?
then we cannot help with that go to that website and create one
or ask the admin of that site to give u one
Maybe you know how to tune the code so I wouldn't have to use prefix and command every time?
like
$number 5
if wrong
6
7
import discord
import os
import music
my_secret = os.environ['TOKEN']
client = discord.Client()
cogs = [music]
client = commands.Bot(command_prefix='!', intents = discord.Intents.all())
for i in range(len(cogs)):
cogs[i].setup()
file "main.py", line 4, in <module>
import music
any1 know the problem?
!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 think music module doesnt exists
i think hes trying to import the cog
hello? can anyone help me with openSea discord bot?
!d help
lmao
Which part of the code would I need to change? @ client.command(pass_context=True) async def number(ctx, z: int): y = randrange(100) await ctx.send('Guess the number!') while True: if y == z: await ctx.send("Congrats!") break await ctx.send("smaller" if (y < z) else "Bigger") return
if what you need is bad internet i can help
replace return with it
gotcha
that pass_context=True is triggering me
so in my case $number discord.ext.commands.Bot.wait_for?
why
cuz its deprecated
huh
remove it
put that in your code
I get an error
then fix your token
\u005c : REVERSE SOLIDUS - \
\u0075 : LATIN SMALL LETTER U - u
\u0032 : DIGIT TWO - 2
\u0031 : DIGIT ONE - 1
\u005c\u0075\u0032\u0031

u sure it should look like this? I dont think so!?
if option.lower() == "helpers":
role = discord.utils.get(guild.roles, name = "Helper")
helpers = ""
for member in guild.members:
if role in member.roles:
helpers += f"{member.name}\n"
await ctx.send(f"Helpers:\n{helpers}")```
why does it show like that ?
@ client.command(pass_context=True) async def number(ctx, z: int): y = randrange(100) await ctx.send('Guess the number!') while True: if y == z: await ctx.send("Congrats!") break await ctx.send("smaller" if (y < z) else "Bigger") !d discord.ext.commands.Bot.wait_for
🤦♂️
await client.wait_for(...)
@slate swan I sent u msg in dm
Ok, never mind. Thanks for the help!
Does anyone have experience with this type of discord bot?
wrong chat lmao
nnaah or?
guild_ids = [I dont wanna send here my id]
@slash.slash(
name="ping",
description="Bot latency.",
guild_ids = guild_ids
)
async def ping(ctx):
await ctx.send(f"Bot Latency = `{round(client.latency * 1000)}ms`")
``` Here is dont have it
No options..
i mean if anyone have experience with API and something like that i can do beginning of the code but i have no idea how to do live events in discord bot and even where to start
mostly yes, because i couldnt find anything like this especially on NFTs
if I can call it like this
it will write who bought NFT when and how much
if u understand 😄
who here can i ask about python decisions (if, else) i have a few questions?
@ client.command(pass_context=True) async def number(ctx, z: int): y = randrange(100) print(" ", y) await ctx.send('Guess the number!') while True: if y == z: await ctx.send("Congrats!") break await ctx.send("smaller" if (y < z) else "Bigger") return
okaay thanks
How do I edit this code in a way that it asks for input unil it is == to answer?
code
which line of the code should I change?
@commands.is_owner
Does this mean serverowner or bot owner?
Bot
role = discord.utils.get(guild.roles, id="891624660012257320") it returns none , but the role is there and id is correct
Remove the quotes
IDs are int
role = discord.utils.get(guild.roles, name = "BankTime") for member in guild.members: if role in member.roles: await ctx.send(len(member))
TypeError: object of type 'Member' has no len() whats wrong?
what u tryna do?
trying to count members with the role
property members: List[Member]```
Returns all the members with this role.
!codeblock
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.
@commands.command()
@commands.is_owner()
async def degrade(self, ctx, user: discord.Member=None):
await ctx.send("Wie will je degraden?")
try:
message = await bot.wait_for("message", check=lambda m: m.author == ctx.author and m.channel == ctx.channel, timeout=190.0)
except asyncio.TimeoutError:
await ctx.send("Helaas reageerde je niet binnen 190 seconde! En de prompt is beeindigd.")
else:
user=message.content
userembed = discord.Embed(title="Helaas, ik heb verdrietig nieuws voor u.", desccription="Afkomstig van: Colza Management")
userembed.add_field(name="Waarom bent u ontslagen?", value="Dit is een inactiviteits wave, en we hebben u voor nu gedegradeerd ivm een tekort aan activiteit.")
userembed.add_field(name="Niet mee eens?", value="Dm @APotato#4553, waarom is dit geen goede reden?")
await user.dm(embed=userembed)
await ctx.send("Het bericht is verstuurd")```
After I send the user I dont get any more response
And I think Its about the user.dm
if option.lower() == "helpers":
role = discord.utils.get(guild.roles, name = "Helper")
for member in guild.members:
if role in member.roles:
await ctx.send(f"Helpers:\n{member.name}")```
why does it send like this?
Sure... That's an API
Idk which tho
bcuz its in a for loop
how can i make it send all name at once?
.join()
^^^
!join
Joining Iterables
If you want to display a list (or some other iterable), you can write:
colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '
However, the separator is still added to the last element, and it is relatively slow.
A better solution is to use str.join.
colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'
An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.
integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
Instead of doing all of that you can just get the role object and join the members.
"\n".join(discord.Role.members)
yup
Ah yea, that
Is there a changelog for discord.py 2.0 somewhere?
yes, but not official
#381965829857738772 message here too
the last update 😦
Alright, thanks!

if option.lower() == "helpers": role = discord.utils.get(guild.roles, name = "Helper") members = '\n-> '.join(discord.Role.members) await ctx.send(members) like this?
How do I do this?
Secretword = hi
async def secretword(ctx):
await ctx.send(hello)
How to make multiple prefixes?
what are you trying to do
When someone types the secret word it will send it but it just says str object is not callable
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
yeah i know
you need a on_message event and check if the message content is the secret word
the response to that
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
secretword = ('crazy')
discord.Guild.fetch_channels = ('channels')
@client.event
async def on_message(ctx):
channels = await ctx.guild.fetch_channels()
if (message.content.startswith(secretword)):
Nope
yeah i know it just has ctx
the parameter passed to on_message in message , so even if you are passing ctx it is an instance of discord.Message
Yea
the way you try to fetch the channel is wrong tho
Instead u can get ctx by await bot.get_context(message)
?
?
SEC_WORD = "word"
@client.event
async def on_message(message):
channel = message.channel
if (message.content.startswith(SEC_WORD)):
await channel.send("lmao")```
if option.lower() == "admins":
roleslist = guild.roles
for role in roleslist:
if "Admin" in role.name:```
i have this code , i am trying to get all the roles which has `Admin` in their name and then getting all the members in those roles, how do i proceed now?
tried it and it gave me a error
help, i am the owner of the server tryna ban my alt
and the error is?
m
code?
@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member : discord.Member, *, reason=None):
emb=discord.Embed(title = "member kicked!", description = f'I have banned {member.name} from the server! Reason: {reason}, color 0xff0303')
emb.add_field(name="responsible moderator", value=f'{ctx.author.mention}', inline = False)
emb.set_thumbnail(url=f'{ctx.member.avatar_url}')
emb2=discord.Embed(title=f"You have been banned from {ctx.guild.name}", color=0xff0303)
emb2.add_field(name="Responsible Moderator:", value=f'{ctx.author.name}', inline=False)
emb2.add_field(name="Reason:", value=f'{reason}', inline=False)
await member.send(embed=emb2)
await member.ban(reason=reason)
await ctx.send(embed=emb)
@ban.error
async def ban_error(ctx: commands.Context,error: commands.CommandError):
if isinstance(error, commands.MissingPermissions):
message = "you are missing the `ban members` permission to run this command"
await ctx.send(message)
elif isinstance(error, commands.MissingRequiredArgument):
message = "ping someone to ban them!"
await ctx.send(message)
elif(error, ArgumentParsingError):
message = "You can't ban your self or anyone that is the same role as you or higher!"
await ctx.send(message)
i tried it before i was here i dont remeber it
then i can't help without knowing the error
m
i did it before i was here im making it in another way
I forgot how to make a command only be able to sent from Dm
@reef shell
i think you need some external 3rd party app to log into a bot
you need a 3rd party app and the bot token i think
but a token will surely be enough
i need help though
can any1 gimme idea of games for discord bot
Yo is discord.py still discontinued?
Or officially? Should I rather say
umm it will always stay like that
forks are a different matter
Man rip
Of to JS lol
it has those i think
@commands.command(aliases= ['purge','delete'])
@commands.has_permissions(manage_messages=True)
async def clear(self, ctx, amount):
await ctx.channel.purge(limit=amount)
embed=discord.Embed()
embed.description = (f"Cleared {amount} messages.")
await ctx.send(embed=embed)```
it gives me an error TypeError: '>' not supported between instances of 'str' and 'int'
Man this brings back memories :)
is this using cogs?
yeah
try amount : int
alright one sec
Yea I still don't like python, but Ye amount : int or str but I think it's int
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
"via discord api"
You want the guilds list?
yes
Mate, are you trying to make a guild list
this is a seperate flask app tho
it works thanks
that's really strong ToS breaking lol
so it doesnt have anything to do with bot.guilds
self-bot?
!d discord.ext.commands.Bot.guilds
property guilds: List[discord.guild.Guild]```
The guilds that the connected client is a member of.
@reef shell can you help me now?
this is a seperate flask app
I haven't used python in so long, but I think it's something to do with list
so it cant access the vars
man im just trying to make my bots website
In?
why do people assume my bots a self bot
hello is it true discord.py got discontinued?
Ye
Yes
Rust is kind of similar, but not as well known, maybe JavaScript
no wonder
tbh
if you want a site for your bot, you should probably use JS instead
for the bot ^
im just trying to login via discord api
and get the guilds count
but why
thats all im trying to do
JS lets you do this easily.
not really
nope, seperate flask app
- banned from gg/python *
you should be python is gud
its not the best ive used
Serenity might be a bit difficult to learn for beginners but aye its better
Lua is cooler
its a python server what do you think?
Used python since 2016 so Idk
But stepped away from the discord module
lua doesnt require indents, thats why i like it more
github link?
half of the people i asked in this server dont know the solution to my question
Lua feels childish lol
how so
Idk just feels like made for kids or seen on TV type
bruh
that sounds bad
you can use them if u want
different styles exist
the syntax in Lua is "harder" I'd say
is pycord reliable?
its not good
how about nextcord?
How it is harder?
its in quotes so its not much harder but its there
they’re all bad
thank you
do u know any good reliable ones atm?
you’re better off using discord.py until discord puts out a breaking change
yupp
how to make prefix if u ping bot
from discord.ext.commands import Bot
from discord.ext.music import MusicClient, WAVAudio, Track
bot = Bot()
@client.command()
async def play(ctx):
voice_user = ctx.message.author.voice
music_client = await voice_user.channel.connect(cls=MusicClient)
track = Track(
WAVAudio('audio.wav'), # AudioSource
'This is audio' # name
)
await music_client.play(track)
bot.run('token') any problems?
yes
a few
you need to give bot a prefix
yeah my friend sent me this he wanted me to check it
and exchange @client.command() with @native granite
Might be, but it doesn't have standard package manager + least community
You have to install 3rd package manager like Luarocks
my one came preinstalled with it
i have an on_message event, is there a way to get a ctx and a message?
cuz i want to do
if ctx.guild.id
``` but i only have message
i need to get the guild id
Luvit is also cool, Lua in NodeJS style
yup, its what i used to make a lua bot
message.guild.id
ok
and await bot.get_context(message) iirc
where does that belong?
this one
ok
message.guild.id
i said that
i finished my bot
: D, who wants to try it
lol
Consider learning OOP
oop?
yes
what is that
bruh
Object oriented programming
thanks
and you can use bot.get_context to get the Context object
@bot.command()async def tt(ctx): a = ctx.message.author.voice.channel await a.connect()
``` why bot not connect user voice channel
wym
said that too
Anyone can help?
just role.members
like that people can ping the bot and then help
like
@past ermine help
so that it displays message
I would need a hand,
i am trying to do some bottno, but importing the libraries it tells me that the module does not exist, even if it has been installed, how do i fix it?
I imported this from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType
Hello, I have command problem. I want to create invite-logger and when I invite someone - it doesn't show. The same with kicking/leaving. What should I do? This is the command now ```python
@client.event
async def on_invite_create(invite,self):
await self.tracker.update_invite_cache(invite)
@client.event
async def on_guild_join(guild,self):
await self.tracker.update_guild_cache(guild)
@client.event
async def on_invite_delete(invite,self):
await self.tracker.remove_invite_cache(invite)
@client.event
async def on_guild_remove(guild,self):
await self.tracker.remove_guild_cache(guild)
@client.event
async def on_member_join(member,self):
inviter=await self.tracker.fetch_inviter(member)
data = await self.client.invites.find(inviter.id)
if data is None:
data={"_id": inviter.id, "count":0,"userInvited":[]}
data["count"]+=1
data["usersInvited"].append(member.id)
await self.client.invites.upsert(data)
channel=discord.utils.get(member.guild.text_channels, name="invites")
embed= discord.Embed(title=f"Welcome {member.display_name}", description=f"Invited by: {inviter.mention}\nInvites: {data['count']}", timestamp=member.joined_at)
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(text=member.guild.name, icon_url=member.guild.icon_url)
await channel.send(embed=embed)```
and how do I repair this?
like make the bots mention a prefix?
yes
discord.ext.commands.when_mentioned(bot, msg)```
A callable that implements a command prefix equivalent to being mentioned.
These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.
if message.content.startswith('cfur info'):
await message.channel.send(embed = discord.Embed(title="Crystal Fur Bot", description='Crystal Fur Bot\nRevision 9\nOwner: Crystal Fur#5411'))
why will the error say it has no perms when it has
can the bot talk in the channel?
yes
why is there self?
show full error I guess
i'm not sure, I watched a tutorial, because I was not sure how to do it
hm
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 15, in on_message
await message.channel.send(embed = discord.Embed(title="Crystal Fur Bot", description='Crystal Fur Bot\nRevision 9\nOwner: Crystal Fur#5411'))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 1065, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The bot is missing permissions.
Read the error for yourself then and decide.
do i have to put it there?
yes
does the channel exist
yes
commands.when_mentioned_or("!") i think.
There would be a different error if it was thag
NoneType has no method send or something
hm
I don't want to be annoying, but can some1 pls help me 🥺
It’s erroring out on send
does the bot have send_messages permission?
So it’s obviously a permission error with the bot not being able to send the message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 155, in help
async def on_member_join(member):
File "/home/runner/GelbieLvl/help.py", line 24, in helpcmd
await ctx.send(embed=embhelp)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/dpy_overrides.py", line 323, in send_override
return await send(channel, *args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/dpy_overrides.py", line 300, in send
data = await state.http.send_message(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
could the attach files be a problem
and many more
@past ermine give it admin
(the bot has admin)
hm
Are you attaching any files in the command?
what
all perms
Those are the permissions
hm
im not
@thin cedar give your bots any permission associated with messages
it has all
Just send messages, embed links, attach files, etc
yup
If it still doesn’t work after giving it everything you fucked your permissions some how.
^^^
or reinvite the bot might be a solution
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 197, in on_message
await client.process_commands(message)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 975, in process_commands
ctx = await self.get_context(message)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 909, in get_context
raise TypeError("Iterable command_prefix or list returned from get_prefix must "
TypeError: Iterable command_prefix or list returned from get_prefix must contain only strings, not function
can we see the code?
hmm ok then debug ur self
thats the only way
wait what
see the typeError
what u passed a function to the prefix?
custom prefix func?
client = commands.Bot(command_prefix=['gl<',"!",discord.ext.commands.when_mentioned], intents=intents, help_command=None,case_insensitive=True)
this is the prefixes
what is this line in the code?
line number?
25
whats in 197 line?
await client.process_commands(message)
mate my idea is
bc it is in an on_message
remove that whenmentioned
yeah, but i wanted to make it a prefix, when the bot is mentioned
u can make it via another method
and i tried <@botid> and Botname#discriminator
first remove that and turn on the bot
yes
tell if the problem comes even after removing?
no
that typerror gone?!
yes
then u may create a on_message function
yes, i already did
what u do is dobt do that name#discr
instead
<@!botid>
try this
doesnt work
mate u must also make another client like
what are you trying
he's trying mention help
ok tell
def get_prefix(bot, message):
prefixes = ["%", "$"]
if not message.guild:
return '$'
return commands.when_mentioned_or(*prefixes)(bot, message)
and commands.Bot(command_prefix=get_prefix)
wait dont use def use async def
?
i use async for my custom prefix function
nothing in there uses await..?
no
hes not awaiting on anything is he? hes just grabbing values that are already there
yup
no need of await
yea then no async def
ty
ok
Hey
@bot.command()async def tt(ctx): a = ctx.message.author.voice.channel await a.connect()
``` bot not join voice channel
why is everything on the same line lmao or is that just me being on mobile
Any errors?
Hi 😄 i have a problem with adding roles to someone if he reacts on msg, there is a problem in line 29 can someone quickly look what is wrong?
there is no payload.guild, use payload.guild_id and Bot.get_guild
Send error then.
Error is ``` PyNaci library needed to use
But how to voice use
did you do pip install discord.py[voice]?
Yes but still error
thanks tylerr ill try
Why you thanking me lol. Blanket is the one who helped you.
….
I tried
anyway still its not working xDD
But not working
You sure you did
pip install PyNaCl
?
What doesnt work? The bot joining the channel or the installation?
!d discord.Client.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
thats what i mean
oh okaaaaaaaaaaaaaay
@sage otter you can give full code my not work
hello
i want ask a question i cant have 2 on_raw_reaction on a discord bot event ?
Hey @hollow mortar!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
No.
You were already told what to do. After installing PyNacI you should of been fine. If the bot isn’t able to join the voice channel still after installing I’d try restarting. If still nothing you did something wrong.
use bot.listen
@sage otter
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").
Example...
Ok i try
thanks man i will look in to it thanks alot
File "/home/container/bot.py", line 110, in on_member_join
await channel2.edit(name=f"Leden: [{bot.guild.member_count}]")
AttributeError: 'Bot' object has no attribute 'guild'
yo i didnt know about this how it worked i searched on it and didnt find anything
any help
@bot.listen()
async def on_message(message):
(some code)
@bot.listen()*
If using bot.event you will need to use process. And this will automatically process It because It only listens and doesnt save everything.
so i should change them both to @bot.listen ?
Yeah,
i changed one of them and still same problem one of them work and the other wont work
oh ok im trying now
Try putting It all In one event.
you could do @bot.listen("on_message") if you need that
didnt work
@bot.listen()
async def on_raw_reaction_add(payload):
if payload.member.id != bot.user.id and str(payload.emoji) == u"📥":
msg_id, channel_id, category_id = bot.ticket_configs[payload.guild_id]
if payload.message_id == msg_id:
guild = bot.get_guild(payload.guild_id)
role = guild.get_role(891031599708266629) #replace role_id with your role's id
for category in guild.categories:
if category.id == category_id:
break
channel = guild.get_channel(channel_id)
ticket_channel = await category.create_text_channel(f"ticket-{payload.member.display_name}", topic=f"A ticket for {payload.member.display_name}.", permission_synced=True)
await ticket_channel.set_permissions(payload.member, read_messages=True, read_message_history=True, send_messages=True)
await ticket_channel.set_permissions(role, read_messages=False, send_messages=False)
message = await channel.fetch_message(msg_id)
await message.remove_reaction(payload.emoji, payload.member)
await ticket_channel.send(f"{payload.member.mention} Thank you for creating a ticket! Use **'-close'** to close your ticket.")
try:
await bot.wait_for("message", check=lambda m: m.channel == ticket_channel and m.author == payload.member and m.content == "-close", timeout=3600)
except asyncio.TimeoutError:
await ticket_channel.delete()
else:
await ticket_channel.delete()```
this is the first event
bot.listen()
async def on_raw_reaction_add(payload):
message_id = payload.message_id
if message_id == 891791302004465665: ## add id msg of the msg you want ppl to react to to get role
guild_id = payload.guild_id
guild = discord.utils.find(lambda g: g.id ==guild_id, bot.guilds)
if payload.emoji.name == 'AU':
role = discord.utils.get(guild.roles, name='AU')
elif payload.emoji.name == 'NA':
role = discord.utils.get(guild.roles, name='NA')
else:
role = discord.utils.get(guild.roles, name=payload.emoji.name)
if role is not None:
member = payload.member
if member is not None:
await member.add_roles(role)
print("done")
else:
print("memeber not found")
else:
print("role not found ")```
thats why
i have the @
no
code shows it doesnt
hi
hello
np
yo
i have this line of code
@commands.Cog.listener()
async def on_message(self, message):
for guild in self.client.guilds:
if message.author.guild_permissions.administrator:
pass
if message.author.guild.default_role.permissions:
if "test" in message.content.lower():
logschannel = self.client.get_channel(892095338075271189)
author = message.author
await message.delete()
await message.channel.send(F"{author.mention} Δεν έχεις perms για να στέλνεις test")
await self.client.process_commands(message)
em = discord.Embed(title="Κάποιος έκανε ένα test!",description='', color=orange)
em.add_field(name = f'{author.name} έστειλε', value= f"{message.content}", inline = True)
await logschannel.send(embed=em)
and i want it when someone has admin, it doesnt delete the message, and if he doent have then it deletes it
how to use custom emojis in discord.py?
my_emoji=client.get_emoji(emoji_id)
await ctx.send(f"{my_emoji}")```
like this emoji "
" is in this server if i want my bot to use it in any server than?
@left dove
it would need to share a server with that emoji
:okay:
i tried my server emoji
??
!!important point
Star / Wildcard imports
Wildcard imports are import statements in the form from <module_name> import *. What imports like these do is that they import everything [1] from the module into the current module's namespace [2]. This allows you to use names defined in the imported module without prefixing the module's name.
Example:
>>> from math import *
>>> sin(pi / 2)
1.0
This is discouraged, for various reasons:
Example:
>>> from custom_sin import sin
>>> from math import *
>>> sin(pi / 2) # uses sin from math rather than your custom sin
• Potential namespace collision. Names defined from a previous import might get shadowed by a wildcard import.
• Causes ambiguity. From the example, it is unclear which sin function is actually being used. From the Zen of Python [3]: Explicit is better than implicit.
• Makes import order significant, which they shouldn't. Certain IDE's sort import functionality may end up breaking code due to namespace collision.
How should you import?
• Import the module under the module's namespace (Only import the name of the module, and names defined in the module can be used by prefixing the module's name)
>>> import math
>>> math.sin(math.pi / 2)
• Explicitly import certain names from the module
>>> from math import sin, pi
>>> sin(pi / 2)
Conclusion: Namespaces are one honking great idea -- let's do more of those! [3]
[1] If the module defines the variable __all__, the names defined in __all__ will get imported by the wildcard import, otherwise all the names in the module get imported (except for names with a leading underscore)
[2] Namespaces and scopes
[3] Zen of Python
like mee6 have custom emojis
shit
to ur server
my bot is in many servers i cannot tell them all to put that emoji :/
ow mean i just misconfused by his words
i thought he is asling about custom emojis so i just told create one
Hello i'm new in conding and i dont khnow how to code this
in a embed it send a reaction when a member click it it sends a message in dms
i just mean like this server have this emoji
how any bot can use a servers emoji in every server
mate its like u need your bot to be in that server where u need to fetch the emoji from
i just want my bot a emoji that is not in the server
btw if u cant add your bot to that server then download that emoji and upload it to your private server where bot is in..
no u cannot
but mee6 also send
my bot cannot fetch emojis?
you are fully aware discord bots are a VERY complex topic and that you will need at least quite a bit of basic python knowledge to get going? main things are OOP and asyncio (at least the basic understanding of the syntax and how they work)?
like this mee6 used a emoji that is not in that server
it can only the servers its on
Hello, I have an error. I want to make invite logger, but there is a problem. When I invite someone - it doesn't show. The same with kicking/leaving. What should I do(pls help)? This is the command now:
@client.event
async def on_invite_create(invite,self):
await self.tracker.update_invite_cache(invite)
@client.event
async def on_guild_join(guild,self):
await self.tracker.update_guild_cache(guild)
@client.event
async def on_invite_delete(invite,self):
await self.tracker.remove_invite_cache(invite)
@client.event
async def on_guild_remove(guild,self):
await self.tracker.remove_guild_cache(guild)
@client.event
async def on_member_join(member,self):
inviter=await self.tracker.fetch_inviter(member) # inviter is the membed who invited
data = await self.client.invites.find(inviter.id)
if data is None:
data={"_id": inviter.id, "count":0,"userInvited":[]}
data["count"]+=1
data["usersInvited"].append(member.id)
await self.client.invites.upsert(data)
channel=discord.utils.get(member.guild.text_channels, name="invites")
embed= discord.Embed(title=f"Welcome {member.display_name}", description=f"Invited by: {inviter.mention}\nInvites: {data['count']}", timestamp=member.joined_at)
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(text=member.guild.name, icon_url=member.guild.icon_url)
await channel.send(embed=embed)```
and how do i repair this?
from discord import <!!>
but why is it needed
if its under 10 guilds itself
is that not against tos?
cant be abused much anyway
hmm
read last line lmao
lol
what this do?
read it's name bruh
creates server
aaaaaa
like what we do
bot create a guild?
lol
i also heard that first time that bots can create server too
than who will be the owner?
and that bot also join that server?
lol confusionnn..
the bot maybe
only bot in server?
:kekw:
than who makes role and how :/
the bot?
i think ctx.author :/
bots can make roles
but by themself?
i mean they make on command
the bot can make it from an event/tasks loop, no
but a owner handle the server by his own
yea anything is possible
still in woder that
wtf this feature
exists
lol
wdym?
discord api for lua
hmm
i wouldnt say so imo
ok gtg bye had nice conversation
okay cya 👋
select(2, check(message, 'respond'))
``` this is nice
thats how you get a certain value from a multiple return statement in lua ofc
can some1 pls help 🥺
@app.route("/dashboard")
async def dashboard():
if not await discord.authorized:
return redirect(url_for("login"))
even if i am authorized i am still getting redirected to login but why and i am using heroku is that the reason?
@patent lark
Calm down, don't ping randoms
sry but his name is something like that
@maiden fable do u know any python lib for ipc
except discord-etx-ipc
multiprocessing.connection
Hello, I have an error. I want to make invite logger, but there is a problem. When I invite someone - it doesn't show. The same with kicking/leaving. What should I do(pls help)? This is the command now:
@client.event
async def on_invite_create(invite,self):
await self.tracker.update_invite_cache(invite)
@client.event
async def on_guild_join(guild,self):
await self.tracker.update_guild_cache(guild)
@client.event
async def on_invite_delete(invite,self):
await self.tracker.remove_invite_cache(invite)
@client.event
async def on_guild_remove(guild,self):
await self.tracker.remove_guild_cache(guild)
@client.event
async def on_member_join(member,self):
inviter=await self.tracker.fetch_inviter(member) # inviter is the membed who invited
data = await self.client.invites.find(inviter.id)
if data is None:
data={"_id": inviter.id, "count":0,"userInvited":[]}
data["count"]+=1
data["usersInvited"].append(member.id)
await self.client.invites.upsert(data)
channel=discord.utils.get(member.guild.text_channels, name="invites")
embed= discord.Embed(title=f"Welcome {member.display_name}", description=f"Invited by: {inviter.mention}\nInvites: {data['count']}", timestamp=member.joined_at)
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(text=member.guild.name, icon_url=member.guild.icon_url)
await channel.send(embed=embed)```
pls help
🙏
i got one but this one looks good too
this is what i used, i was messing around with ipc earlier and it's really simple
ipc is good too but i am trying to do something else
you asked for ipc lol
i mean i want something for communication
can you elaborate because thats what ipc is
i saw that
inter process communication
yes