#discord-bots
1 messages · Page 688 of 1
haha, Its probably like 60ms for me, my bot is rn searching from over 10 subreddits * 9 with praw api
are you using asyncpraw?
You mean the reddit api?
its called praw yeah 😄
Praw is just an api wrapper with a async version which is asyncpraw
i think u can use the api directly instead
I like calling it the reddit api
i mean you aren't wrong.
Even the docs calls itself the reddit api
Just use asyncPRAW its literally the same thing, just asynchronous
why go through the hassle of creating requests when there is a library to do it for you?
cus there is an api
Yeah its just unnecessary
oh yeah and its also got a infinite loop * 9
i mean its a feesible option, just not always the best. as a library can handle eventualities that you may not consider.
Wdym
You don't need to reinvent the wheel
^
I want to make a api wrapper for the reddit api or a asyncpraw fork but idk if i should start 
Are you sending multiple images at a time?
i mean there are an endless amount of libraries that need to be made ||I have a project that needs a Python library|| 🤣
its taking img from praw and making a embed
Yes i know but wdym by a loop
a meme command.
Ive made a search command with asyncpraw lol
while loop so it keeps sending the imgs 24/7
Will probably get you ratelimited if you constantly do it
same, did a meme command for a bot a while back, had it where it searched a set of subreddits, or you could enter your own to search 😄
unlikely
Bad thing about asyncpraw using the multiple reddit instance makes it very slow
why not just make it a background task using ```py
@tasks.loop()
I mean I've got like 3 websites and 1 game server running on the same vds
and only 4gb 2cores
I think using the multiple reddit instance and when you use a limit of subs it will look for the limit in total for all the subreddits and not the limit per subreddit idk
yep so just use aiohttp
Nah
Dont want to🚶
🕴️
the latency is so bad I thought my command didn't work and went back to coding, after realising that it was just taking shit ton of time to work lol
Damn
asyncpraw is slow ig
Not really
I used it before but forgot what performance was like
Depends on how much subreddits your searching and how many submissions your going through but getting a random sub is very quick
aiohttp can get 100 subs in a second
and
reddit = asyncpraw.Reddit( client_id="CLIENT_ID", client_secret="CLIENT_SECRET", password="PASSWORD", user_agent="USERAGENT", username="USERNAME", )
it doesn't require any of that
no auth
🤷♂️
is there a function that returns thr name of the last command/event that ran?
At your service
member was not found
discord.ext.commands.errors.MemberNotFound: Member "deleted-role" not found.
is delete_after= in seconds or minutes
cuz its taking shit ton of time to delete itself for some reason
Secs as ints
I think it gets ints and floats idk
I have
await channel.send(content=None, embed=embed, delete_after=1)
Or only floats
and it takes like 30 sec to delete
or 15s

Did you actually add the member
And do you have intents and is the bot higher than the role the member has
for guild in client.guilds:
for channel in guild.channels:
if os.path.exists("/home/bot/adx/channel"+str(guild.id)) == True:
file = open("channel"+str(guild.id), "r")
if str(channel.id) == file.read():
embed = discord.Embed(title="Channel inactive", description="Send a message to refresh", color=0xFF0000)
embed.add_field(name="Reason for inactivity:", value="Restart by developer", inline=False)
embed.add_field(name="Note: ", value="Everything should be working now.", inline=False)
await channel.send(content=None, embed=embed, delete_after=1)
break
I have this in on_ready so whenever my bot crashes(every damn second), it sends that so ppl think im just deving the bot and my servers arent shitty
^
What about it
Can your bot kick others?
And is the bot higher in roles than the users your trying to kick
Answer my question
why add kick command
kinda useless just right click
All these questions are related to the problem if not answered i cannot help you out understand?
and kick user
^ now?
Try printing out all members
await ctx.send(ctx.guild.members)
No send it in a different command
To do something apart from replying to the interaction, would I use interaction.response just like for replying to the interaction, or would I have to use something else?
@bot.command()
async def test(ctx):
await ctx.send(ctx.guild.members)
You want it to send an individual msg?
by something apart from replying I mean like kicking a user, deleting a channel, creating a channel, deleting a message
. @slate swan
what would I use tho?
would I just use interaction.response?
and then something like interaction.response.category.create_channel("channel name")?
Interaction is enough
ok
Response is for responding to a msg
Looking for some help please on how to do something.
i want to make a discord bot that sends messages every so many minutes but I want to be able to create multiple messages with different time intervals
I know i can use tasks..loop to send a message every so many minutes, but it's a question of how would i actually store every message, different times and cycle through them and post. Obviously tasks.loop requires a timeframe so e.g tasks.loop(minutes=10)
yeah, that is why I was asking
interaction.guild
@bot.command(name = "test")
async def _test(ctx):
try:
await ctx.send(f"Random tekst here {ctx.author} ")
I think interaction has all the attr ctx has
Wont work
Plus no need for a try and except and your missing an exception
!e
@client.command(name = "test")
async def _test(ctx):
try:
await ctx.send(f"Random tekst here {ctx.author} ")
message = {
"content" : f"Random message {ctx.author} "
}
requests.post(config['Webhookurl'], data=message)
except(ValueError):
await ctx.send("***not vallid***")
@umbral dome :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'bot' is not defined
how to make
if any(word in message.content for word in list):
```not case sensitive
Just why
!e
@client.command(name = "test")
async def _test(ctx):
try:
await ctx.send(f"Random tekst here {ctx.author} ")
message = {
"content" : f"Random message {ctx.author} "
}
requests.post(config['Webhookurl'], data=message)
except(ValueError):
await ctx.send("***not vallid***")
how would I create a channel in a particular category tho, because It wouldn't work if I do something like this:
category = ...
await interaction.category.create_channel()
as it would think that .category is a sub class/program of interaction
@umbral dome :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'client' is not defined
Dont really know
Not familiar with category an its attrs
how 
Read the docs. It's guild.create_text_channel and category is a kwarg
actually, I don't think that I need to use await interaction, because all of this code is already inside the callback
that is not the problem that I had
the problem is that I needed to do it after the interaction
and I just don't really know how to work with interactions
Just do @tacit horizon
if any(word in message.content.lower() for word in list):
I can't give you anymore information, I've told you it's interaction.guild
look up guild.create_text_channel
for how to do it in a category
maybe u can use sets
Looking for some help please on how to do something.
i want to make a discord bot that sends messages every so many minutes but I want to be able to create multiple messages with different time intervals
I know i can use tasks..loop to send a message every so many minutes, but it's a question of how would i actually store every message, different times and cycle through them and post. Obviously tasks.loop requires a timeframe so e.g tasks.loop(minutes=10)
!d itertools.cycle
itertools.cycle(iterable)```
Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. Roughly equivalent to:
```py
def cycle(iterable):
# cycle('ABCD') --> A B C D A B C D A B C D ...
saved = []
for element in iterable:
yield element
saved.append(element)
while saved:
for element in saved:
yield element
```...
and use next every new cycle.
btw, how would I pass variables into my own View class
nice 
Makes the message content all lower case and if its in the list it will continue
ya

if any(word in message.content for word in wrod1):
await message.channel.send("No")
if anyone say that word, then i want to add his name in a list.
and how many time he said that .
@slate swan help !! 😅
Im lurking 🕴️
its OOP
why ;-;
ya
You can use a db or json
Json would be fine since your storing an int key with and int value
Json !!!!

javascript ?
json is python module
and its look like javascript ?
how would i add a role to a user if i have their id?
can u make it in simple python form not in discord form
with input()
huh
Wdym by using input()
await add_roles(role)
but what about the user?
!d disnake.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://docs.disnake.dev/en/latest/api.html#disnake.Role "disnake.Role")s.
You must have the [`manage_roles`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.manage_roles "disnake.Permissions.manage_roles") permission to use this, and the added [`Role`](https://docs.disnake.dev/en/latest/api.html#disnake.Role "disnake.Role")s must appear lower in the list of roles than the highest role of the member.
you would have to fetch the user first, which would look something like this:
user = await bot.fetch_user(user_id)
await user.add_roles(role)
is it the role id?
This will only work on member objects*
yeah, I think so
oh yeah true, so it would have to be fetch_member, sorry
im getting AttributeError: 'Bot' object has no attribute 'fetch_member'
Type hint an arg with a membee obj and add the role with it
Because thats not a thing afaik
what should it look like?
cause idk what type hinting is
use get_member
instead of fetch_member?
yeah
i get the same Attribute Error
(with get_member not fetch_member)
show code
user = await bot.get_member(userid)await user.add_roles(913137354900897792)
it depends on what they're using, but I'm assuming they're using bot
i am
so...get_member returns an attribute error?
userid = user.id
user = await bot.get_member(userid)
await user.add_roles(913137354900897792)
ye
k
does it work?
i got TypeError: object Member can't be used in 'await' expression
it's not async
no await
just ctx.guild.get_member(userid)
k lemme try it
i got AttributeError: 'int' object has no attribute 'id'
hmm
can I change embed.set_image size somehow?
I mean how do I make the embed bigger?
is user ctx.author?
? make the embed bigger?
u don't
ah
at least i think
no
its a mentioned person
who is user.id
ah
the id of the mentioned person
is user: discord.User?
ye
ok
ohh
because user is already the mentioned person, you dont need a get_member
just add it directly, because you did a user: discord.User
userid = user.id
await user.add_roles(...)
... do you really need the user id?
@dire folio
nope
@velvet tinsel i'm getting AttributeError: 'User' object has no attribute 'add_roles'
hmm
Add roles only takes member objs
try await bot.add_roles(userid, role)...Okimii?
thank god you're here
I can finally go sleep
no
await member.add_roles(role)
Wdym
member is discord.Member?
If you name it that yes
pepe:discord.Member
Pepe is a member obj
Yes their is a user but add roles doesnt take that type
Yw
.bm
can i get an id from that, cause i need the id
Yes
The member obj takes ids and usernames
😅
🕴️
if any(word in message.content for word in wrod1):
``` how do i get the user name who type that word
i have to add ctx
but how ;-;
@velvet tinsel read this
https://www.python.org/dev/peps/pep-0484/
i get AttributeError: 'int' object has no attribute 'id
where do i put thissssssssssssss
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: None is not in list
In any(iterable)
async def accept(ctx, user: discord.Member, role):
userid = user.id
await user.add_roles(913137354900897792)
still not get it 😣
Iirc it only takes the names of the roles
ohh
now i'm getting AttributeError: 'str' object has no attribute 'id'
async def accept(ctx, memberr: discord.Member, role):
await member.add_roles(role)
That should work
ty
for the id is it just member.id?
No just add the member id when you call the comamnd
the member id changes tho
Never does
A member id never changes but a member username could
no cause its going to be for different users
Then add a different id
How you should call the command
!accept 1234567890 role
Dont knoe your prefix so i used ! Lol
so use the id instead of the mention?
Yes
it doesn't do the intended thing
heres the command:
async def accept(ctx, member: discord.Member, role):
userid = member
print(userid)
for item in waiting:
if item[0] == userid and item[1] == 'hoster' and role == item[1]:
role = item[1]
emb = discord.Embed(title='**Accepted**', description=f'Congratulations you have been accepted for {role}!', color=0x2ecc71)
await member.send(embed=emb)
await member.add_roles("Hoster")
emb = discord.Embed(title='**User has been accepted!**', description='The neccessary roles have been added.')
await ctx.send(embed=emb)
str(role)
waiting.remove([userid, role])
save_waiting()
return
elif item[0] == userid and item[1] == 'staff' and role == item[1]:
role = item[1]
emb = discord.Embed(title='**Accepted**', description=f'Congratulations you have been accepted for {role}!', color=0x2ecc71)
await member.send(embed=emb)
urole = discord.utils.get(bot.get_guild(ctx.guild.id).roles, id = 763000301467992084)
await member.add_roles(urole)
urole = discord.utils.get(bot.get_guild(ctx.guild.id).roles, id = 760101679877849089)
await member.add_roles(urole)
emb = discord.Embed(title='**User has been accepted!**', description='The neccessary roles have been added.')
await ctx.send(embed=emb)
str(role)
waiting.remove([userid, role])
save_waiting()
return
else:
await ctx.send('No user found!')
i haven't changed the elif part
the list looks like [[1212341231, 'hoster']]
you should be able to just mention a member and pull their ID from the mention as long as you type hinted it properly.
how do i get the user id that used the command?
user_id = ctx.author.id
alright thanks
how would i do that?
async def accept(self, ctx, memberr: discord.Member, role: discord.Role):
member_id = memberr.id
role_name = role.name
Type hinting like i did above for both memberr and role allows you to mention the role or memberr by @, ID, or its exact name and receive the entire object for it. Note: any exact names that have spaces need to be incased in quotation marks so your command knows its one arg.
how to check if someone mentions my bot. and if they do the bot will send a message
how would i make a reminder command i was thinking using asyncio.sleep() because its a private bot but im not because its kinda bad practice so how would i?
my while loop doesn't go thru completely for some reason it just stays at the start and restarts itself
Let's see the code then
its kinda nsfw but aigh
while autoporn:
if message.channel.is_nsfw():
if os.path.exists("/home/bot/adx/channel"+str(message.guild.id)) == True:
file = open("channel"+str(message.guild.id), "r")
if str(message.channel.id) in file.read():
post = reddit.subreddit("legalteens").random()
while post.url == None or "redgif" in post.url:
print("skip")
post = reddit.subreddit("legalteens").random()
embed = discord.Embed(title="r/legalteens")
embed.set_image(url=post.url)
await message.channel.send(content=None, embed=embed)
post = reddit.subreddit("hentai").random()
while post.url == None or "redgif" in post.url:
print("skip")
post = reddit.subreddit("hentai").random()
embed = discord.Embed(title="r/hentai")
embed.set_image(url=post.url)
await message.channel.send(content=None, embed=embed)
#
post = reddit.subreddit("zerotwohentai").random()
while post.url == None or "redgif" in post.url:
print("skip")
post = reddit.subreddit("zerotwohentai").random()
embed = discord.Embed(title="r/zerotwohentai")
embed.set_image(url=post.url)
await message.channel.send(content=None, embed=embed)
# ```
would await asyncio.sleep() work as fix for
aiohttp.client_exceptions.ClientOSError: [Errno 104] Connection reset by peer
or does it need to be time.sleep()
could u check this pls.
async def accept(ctx, memberr: discord.Member, role: discord.Role):
userid = memberr.id
for item in waiting:
if item[0] == userid and item[1] == 'Hoster' and role == item[1]:
emb = discord.Embed(title='**Accepted**', description=f'Congratulations you have been accepted for {item[1]}!', color=0x2ecc71)
await memberr.send(embed=emb)
await memberr.add_roles("Hoster")
emb = discord.Embed(title='**User has been accepted!**', description='The neccessary roles have been added.')
await ctx.send(embed=emb)
str(role)
waiting.remove([userid, role])
save_waiting()
return
cause it doesn't seem to be working
what are you inputting for the role when you run the command?
Hoster ?
so you get a role object to use then. so instead of:
await member.add_roles("Hoster")
Which wouldn't work anyways as it takes a role object.
do:
await member.add_roles(role)
also your if statement looks a bit wonky.
if item[0] == userid and item[1] == 'Hoster' and role == item[1]:
has you checking the same thing twice essentially.
try:
if item[0] == memberr.id and item[1] == role.name:
... do stuff
Also have you considered a database by chance? i don't mean to put you down, but your code looks a bit inefficient with the for loop. May be better to store anyone waiting for a role in a database where you can store the userId as the primary key, the role id as the role they are waiting for and their status as "waiting", "accepted", or "denied". This could easily be done using SQLite or PostgreSQL
how can i make a check that checks if the interaction author is the context author?
what is the code? is there a callback? like res or something? you could do:
if res.author.id === ctx.author.id:
...some stuff
trying to do a button that only is valid when the context author interacts with it
dont have a tb since i havent started
you should get a return of essentially context with the interaction and you can check that as it should return who interacted if the person who interacted isn't the author of the command then pass else execute code.
may i get an example i have 0 idea what your talking about mr fancy words
oh gosh its been a bit since i've used buttons in python 😂
#1
def filter(res):
return res.author.id = ctx.author.id
try:
while True:
res = await self.bot.wait_for('Button_click', check=check, timeout = 500)
if clause == true:
...execute code
except asyncio.timeoutError as e:
...handle it
remember its all psuedo. depends on the lib and everything.
im using disnake lol
oh then i have no clue. brb.
damn😭
what type of interaction.
wdym what type
Since you are using disnake, which is a fork of discord.py you have View.interaction_check
i do?
!d discord.ui.View.interaction_check
await interaction_check(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns `True`.
Note
If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
🚶
This works the same way as the cog check you get inside of Cogs
Just store a ctx instance variable to your view class
Then use it inside of the interaction_check
E.g ```py
return self.context.author == interaction.author
thank god andy was here 😂 i got docs open trying to bash my way through it to try and find an answer 😂
This will cause all children of the view to only run if the ctx author is the one pressing the button/interaction
wdym?
MyView(ctx)
oh
in the class right
You'd subclass View and give it a ctx parameter inside of the class constructor
alr thx
I made a discord bot that allows you to ask it to write code and explain how code works using the openAI API. I'd love some feedback on what I have so far! https://github.com/DH711-creator/ai-discord-bot
You'd probably want to use an async driver for OpenAI engines
If there is one, otherwise run it inside of executor
As this would block your bot for the amount of time it takes to compute results
works thanks andy
oh and @brittle ingot thx for effort
how would i make it add multiple roles
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
you can give it a list of roles to add.
you can only add roles as a list and not a single role
*roles means you can add any amount of roles
like their isnt something like add_role
my bad it was kinda bad written
how would i separate the role names
coma
I have made my own View class, and I'm trying to pass variables into it, but for some reason I get this error: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'View' object has no attribute 'children'
This is how it looks. Did I do it the wrong way? and how can I fix it?
class View(View):
def __init__(self, ctx, category):
self.ctx = ctx
self.category = category
view = View(ctx, category)
as any string
what lib?
pycord
welp dont know
what lib do you use?
wonderful, thank you
You need to construct the super class
isn't that only used to make timeouts?
oh, ok, so would I just write something like super().__init__(ctx, category)?
under def init
No, because the superclass doesn't take ctx nor category
Those are your custom stuff so you don't pass it to the superclass
class View(View):
def __init__(self, ctx, category):
self.ctx = ctx
self.category = category
def super().__init__(timeout=None):
what is the point of it then?
alright, I'll try it, give me a sec
it wont work
ok, it worked, thank you guys
i did await memberr.add_roles('Trial Mod', 'Staff') and got the error
Ignoring exception in command accept:
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 976, in accept
await memberr.add_roles('Trial Mod', 'Staff')
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/member.py", line 777, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'str' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/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: 'str' object has no attribute 'id'
also, if I wanted to make a private command, that can only be used by a user with a certain role, would I just add a @has_role() decorator into the command?
yup
ok, thanks
yw
is it an interaction?
Your passing strings, not discord.Role objects
no its an event?
You want to get the user which caused the error?
yup
how do i pass them as discord.Role objects?
You'd do ctx.author then
surely you should be able to do something like ctx.author
Since you get that in on_command_error
if you pass in ctx into the event
You'd need to get the role,
You can do so via get_role
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
i tried but i got no response from the error handler
Can you show the code?
@bot.event
async def on_command_error(ctx,error):
view = buttons.tb(ctx.author)
if isinstance(error, commands.CommandNotFound):
embed8 = disnake.Embed(title="Error!!!",
description=f"Could not continue",
color=0xe74c3c,
timestamp=datetime.datetime.utcnow())
await ctx.send(embed=embed8,view=view)
await view.wait()
if view.value is True:
embed9 = disnake.Embed(title="Terminal",
description=error,
color=0xe74c3c,
timestamp=datetime.datetime.utcnow())
await ctx.send(embed=embed9)
in your params
role: discord.Role
And it works when you don't give an author?
yep
class Tb(disnake.ui.View):
def __init__(self,author: disnake.Member):
self.author = author
super().__init__(timeout=10.0)
self.value = None
async def on_timeout(self):
self.children[0].disabled = True
self.stop()
@disnake.ui.button(label="Traceback",style=disnake.ButtonStyle.red)
async def traceb(self,button:disnake.ui.Button,intr: disnake.MessageInteraction):
await intr.send("Loading Traceback...",ephemeral=True)
self.value = True
self.children[0].disabled = True
self.stop()
thats the class
Where exactly are you using the author though
And I don't see anything here that would cause an error
Is there no error raised and it just hangs?
nope
nvm lol
!d discord.TextChannel.mention
property mention: str```
The string that allows you to mention the channel.
Got no clue then, maybe try putting the class construction inside of a try-except to see if you maybe get an error out
alr
so would I just do something like channel.send("message " + discord.TextChannel.mention(some_channel))
or what? I don't really get it
wait were exactly?
or would it just be: channel.send("message " + discord.the_channel_that_I_want_to_mention.mention)?
Nope its a property so
Just channel.mention
so somethingl like this would work?
channel here being a discord.TextChannel instance
shit, wrong mention
ok, thanks
Inside of the error handler
ah mb
nope no error was raised
I got no clue then
damn
works on commands but not on the event
@slate swan is that a slash command or a normal command?
Cuz slash commands has a diff global command handler
how can i make a util which returns X based on what i input eg:
content = "--do ban --do kick"
util.args(content, "--do")```
i want to make it return **ban** anyone know how i can do this
command error event
normal command
Oh ok
yeah
Looks like they changed up the ClientUser object in 2.0
thanks you
What's happened - fork?
typo?
not that init
your doing buttons right
yea
because if your doing buttons the kwarg is style
ohhh, yea. Didn't notice, thanks
yw
idk who pinged me but i was afk sorry.
ik i downloaded it
close and open your editor
thanks
and use aiohttp request isnt async
plus im in this server and they are beta testing a bot, They want people to add the bot to their servers to test it. The bot requests Administrator permissions, but has only Help, info, bot info, support and thats it. Its supposed to be a raid prevention bot. Am i the only one who thinks it sounds fishy?
!pypi aiohttp
nah thats really fishy
yeah
It's either their doing something not good, or they could just not be educated on why not to give bots admin
i think they're trying to get the bot in 75 servers to get the verification process going. but #1 never give a bot admin perms. #2 why beta test with none of the needed commands for the bot to actually function...
the team leader of the development team is a discord verified bot developer 👀
😐
still you shouldnt give a bot admin perms
oh i know lol
all of my bots need admin perms
mhmm bet

no offense if it actually needs it then great, but like i see so many people using it as a way to bypass actually giving their bot the permissions they should need at a minimum. you know? Like one of the first things i do is sit down and say. What will my bot do? What permissions does it need to do that?
i just give it admin perms for the future i wont need to re invite it
Kek, thats the last thing I think of
really?
im to lazy to do it lol
Can't you just add permissions to it's bot role?
to lazy🚶
😐
Yep, I'm pretty lazy as well
relatable
I've made auto permissions calculators before just so I don't need to think that much
what does that mean
should be requests.get() right?
how can i make a util which returns X based on what i input eg:
content = "--do ban --do kick"
util.args(content, "--do")```
i want to make it return **ban** anyone know how i can do this
dpy v2.0
lol
then u can use components=
u need to use view=
and then u need to make a class for ur button view
not me lol
what
you replied to me
a subclass
oh 😭
brah
what
u have so many problems in that code
just saying you should use aiottp
im just watching a video on how to create my first bot
and dont do this read python docs & dpy docs
so switch requests with aiottp
!pypi aiohttp
yep since dpy is an async lib
its a bit different
okay
so instead of request.request it would be aiohttp.ClientSession()
yep
prob not but it will help ur bot run better
okay
it will not block the code
My discord bot controls a UI, so on my main thread I start a tk window and then fork off a thread to run the bot. I pass to that thread a reference to an object with methods that the bot can call to trigger things on the UI. I'm getting a really confusing error from the bot's thread.
Exception in thread TheClicker:
Traceback (most recent call last):
File "C:\Users\m\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner
self.run()
File "C:\Users\m\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\m\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1652, in cget
return self.tk.call(self._w, 'cget', '-' + key)
TypeError: can only concatenate str (not "int") to str
the place my bot thread starts is here:
root = tk.Tk()
player = ChannelSurfTk(root, rng, playlist)
def OnClose():
global exit_code
player.OnClose()
exit_code=EXIT_USER
import threading
from time import sleep
threading.Thread(
group=None,
target=discord.main,
name='TheClicker',
args=(player), kwargs={},
daemon=True
).start()
and discord.main is
def main(ui_hooks):
print("here0")
return DiscordChannelsurf(ui_hooks, cfg.TOKEN)
but not even "here0" is being printed. I can't figure out what is causing cget to be called with an incorrect parameter. The bot doesn't even call any tk methods, I commented out the few places it uses ui_hooks while trying to debug this.
Why am I getting an error if I reinstalled the library with version 1.7.3?
After all, 1.7.3 components should work
how do i get the bot's role
how can i get a commands required permissions?
dont use 3rd party libs, they kinda break dpy instead use a fork of dpy or use dpy 2.0
How to send buttons in dpy 2.0?
how to make the buttons line up?
@bot.command(aliases = [])
@commands.cooldown(1, 1, commands.BucketType.user)
async def emb(ctx, **kwargs):
await ctx.message.delete()
msg = await ctx.send(
embed = discord.Embed(title = 'Русский / Enlish', timestamp = ctx.message.created_at),
components = [
Button(style = ButtonStyle.green, label = 'Русский'),
Button(style = ButtonStyle.red, label = 'English')
])
responce = await bot.wait_for('button_click', check = lambda message: message.author == ctx.author)
components = [
[Button(style = ButtonStyle.green, label = 'Русский'),
Button(style = ButtonStyle.red, label = 'English')]
])
or use ActionRow
Thank you!
view kwarg in .send()
your welcome
https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py#L16-L35 take a look at the example here
omg
What if I use a different library with buttons?
dislash
disnake has good buttons lol
import discord
from discord.ext import commands, tasks
from datetime import datetime
import random
from itertools import cycle
client = discord.Client()
status = cycle(['Minecraft', 'Roblox', 'Pie', 'Fortnite'])
@client.event
async def on_message(message):
change_status.start()
if message.author == client.user:
return
if message.content.startswith('hi'):
await message.channel.send('hi')
if message.content.startswith('time'):
datem = datetime.today().strftime("%m/%d/%y")
await message.channel.send(datem)
if message.content.startswith('user'):
await message.channel.send(message.author)
if message.content.startswith('daball'):
r = ['Yes', 'No', 'Fifty percent']
await message.channel.send(random.choice(r))
@tasks.loop(seconds=10)
async def change_status():
await client.change_presence(activity=discord.Game(next(status)))
client.run(token)
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
What do u guys think? It edits your cloudflare ddos settings on your webites https://media.discordapp.net/attachments/829419223977426962/921577010839572511/21-12-17-18-22-17.mp4
does interaction have all the attrs that ctx has?
No
i mean if you want ctx just pass an argument to the class
ic thank you ill search up docs to see all of them
yeah ik
how can I edit Embed from msg in msg2?
msg = await ctx.send(
embed = discord.Embed(title = 'Выбирите язык\nSelect language', timestamp = ctx.message.created_at),
components = [
[Button(style = ButtonStyle.blue, label = 'Русский'),
Button(style = ButtonStyle.blue, label = 'English')]
])
responce = await bot.wait_for('button_click', check = lambda message: message.author == ctx.author)
if responce.component.label == 'Русский':
msg2 = await ctx.send(
embed = discord.Embed(title = '', timestamp = ctx.message.created_at),
components = [
[Button(style = ButtonStyle.blue, label = 'Русский'),
Button(style = ButtonStyle.blue, label = 'English')]
])
i tried with msg.edit() but it not work
Save the object
You did so it will be msg2 not msg
getting 400 client error when sending webhooks
means that my ip is prolly flagged for sending too much i assume?
yo guys, how can my bot fetch when someone joins vc, and liek their id or name
!d discord.on_voice_state_update || member = member. Where member is an instance of discord.Member. name, id = member.name, member.id
discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceState "discord.VoiceState").
The following, but not limited to, examples illustrate when this event is called...
gotcha
is before and after option args?
I just finished making a bot that checks for Steam sales. I wanted to make it public on GitHub but I don’t know how to hide my token. Can someone help?
no, has to be async def on_voice_state_update(member, before, after
alr
are you proficient with github?
just dont post the token or use an env file or just be a weirdo like me and use a py file to import the var lol
you can make a file just called hidden.py, put token in it and import the token into main file from it. before pushing, make a file called .gitignore and just put hidden.py in it
Alright, thanks.
this will stop the hidden.py from being pushed to the repository - but code will still work fine
Yeah I know enough to understand gitignore but I didn’t know if something more complicated would be needed
nope that should be all
just from hidden import TOKEN where TOKEN is a variable in hidden.py
client/bot.run(token)
utils.get
how can I move members into a different vc w/ the bot?
!d discord.Member.move_to
await move_to(channel, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Moves a member to a new voice channel (they must be connected first).
You must have the [`move_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.move_members "discord.Permissions.move_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.edit "discord.Member.edit").
Changed in version 1.1: Can now pass `None` to kick a member from voice.
why when the bot switches to 2 if it gives such an error?
msg_1 = await ctx.send(
embed = discord.Embed(title = 'Выбирите язык\nSelect language', timestamp = ctx.message.created_at),
components = [
[Button(style = ButtonStyle.blue, label = 'Русский'),
Button(style = ButtonStyle.blue, label = 'English')]
])
responce = await bot.wait_for('button_click', check = lambda message: message.author == ctx.author)
if responce.component.label == 'Русский':
msg2 = await msg_1.edit(
embed = discord.Embed(title = '2', timestamp = ctx.message.created_at),
components = [
[Button(style = ButtonStyle.blue, label = 'Русский'),
Button(style = ButtonStyle.blue, label = 'English')]
])
async def on_member_join(member: discord.Member):
role = member.guild.get_role(893297001897295942), (example123123123123)
await member.add_roles(role)```
how could i make it so that it gives a user two roles when they join?
i dont think i've done it correctly
give two roles
how lol
the same way you gave/got the first role
yes
ok thx
is there a way i can make this only call once because it seems its getting called for as many mutual servers as the user like im in 3 servers with the bot and its getting called 3 times any way i can make it only get called once?
@commands.Cog.listener()
async def on_presence_update(self, before, after):
return print(f"User: {before} > before: {before.status} - after: {after.status}")```
https://cdn.discordapp.com/attachments/921522898773114922/921599904332275732/unknown.png **im using Pycord**
File "c:\Users\thoma\Desktop\discord.py\python\bot.py", line 320, in <module>
client.load_extension(f'Cogs.{filename[:-3]}')
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 674, in load_extension
spec = importlib.util.find_spec(name)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\importlib\util.py", line 94, in find_spec
parent = __import__(parent_name, fromlist=['__path__'])
ModuleNotFoundError: No module named 'Cogs'```
Anyone
?
Hello
shut the fuck up
is there a way i can make this only call once because it seems its getting called for as many mutual servers as the user like im in 3 servers with the bot and its getting called 3 times any way i can make it only get called once?
@commands.Cog.listener()
async def on_presence_update(self, before, after):
return print(f"User: {before} > before: {before.status} - after: {after.status}")```
https://cdn.discordapp.com/attachments/921522898773114922/921599904332275732/unknown.png **im using Pycord**
Excuse me
File "c:\Users\thoma\Desktop\discord.py\python\bot.py", line 320, in <module>
client.load_extension(f'Cogs.{filename[:-3]}')
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 674, in load_extension
spec = importlib.util.find_spec(name)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\importlib\util.py", line 94, in find_spec
parent = __import__(parent_name, fromlist=['__path__'])
ModuleNotFoundError: No module named 'Cogs'```
shut up brah
is there a way i can make this only call once because it seems its getting called for as many mutual servers as the user like im in 3 servers with the bot and its getting called 3 times any way i can make it only get called once?
@commands.Cog.listener()
async def on_presence_update(self, before, after):
return print(f"User: {before} > before: {before.status} - after: {after.status}")```
https://cdn.discordapp.com/attachments/921522898773114922/921599904332275732/unknown.png **im using Pycord**
im predicting a mute in +/- 2 min
shut the fuck up lil boy
this why u a skid brah https://github.com/CaedenPH
luh brah named caeden 😛
you just ping mods and theyll mute him
no kizzap ur so cringe "abusing me!!" like shut up brah
<@&831776746206265384>
<@&831776746206265384> this guy hacking me
hm maybe even a temp ban
<@&831776746206265384>
What's going on here?
!mute 913724640021594142 Investigating
that would be nice
:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1639802647:f> (59 minutes and 59 seconds).
He was abusing me when i havent done anything
You can, you can send a DM to @novel apex if you'd like to explain what's up in private
pls search
Its all good now hes muted
pls beg
now
Can you help me with my code tho?
sure
File "c:\Users\thoma\Desktop\discord.py\python\bot.py", line 320, in <module>
client.load_extension(f'Cogs.{filename[:-3]}')
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 674, in load_extension
spec = importlib.util.find_spec(name)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\importlib\util.py", line 94, in find_spec
parent = __import__(parent_name, fromlist=['__path__'])
ModuleNotFoundError: No module named 'Cogs'```
if filename.endswith("Cogs1.py"):
client.load_extension(f"Cogs.{filename[:-3]}")
oh wow
report
woah whatd i miss
😳
LOL
use os.dir
@scarlet spear yes
os.listdir("cogs") no need for .\Cogs
File "c:\Users\thoma\Desktop\discord.py\python\bot.py", line 328, in <module>
for filename in os.dir(".\Cogs"):
AttributeError: module 'os' has no attribute 'dir'```
if filename.endswith("Cogs1.py"):
client.load_extension(f"Cogs.{filename[:-3]}")
!d os.listdir
os.listdir(path='.')```
Return a list containing the names of the entries in the directory given by *path*. The list is in arbitrary order, and does not include the special entries `'.'` and `'..'` even if they are present in the directory. If a file is removed from or added to the directory during the call of this function, whether a name for that file be included is unspecified.
*path* may be a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object). If *path* is of type `bytes` (directly or indirectly through the [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike "os.PathLike") interface), the filenames returned will also be of type `bytes`; in all other circumstances, they will be of type `str`.
This function can also support [specifying a file descriptor](https://docs.python.org/3/library/os.html#path-fd); the file descriptor must refer to a directory.
Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `os.listdir` with argument `path`.
whats for the path? do i specify the file name
from discord.ext import commands
import os
class TestCog(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@commands.is_owner()
async def reload(self, ctx, cog: str):
try:
self.bot.unload_extention(cog)
self.bot.load_extention(cog)
except Exception as e:
await ctx.send("Could not reload cog")
return
await ctx.send("Cog reloaded")
def setup(client):
client.add_cog(TestCog(client))
print(f"Background is loaded")```
Is this right?
#unban bubba he did nothing at all
<@&831776746206265384> bubbas friends are here now
!mute 921053014981234759 inv
:incoming_envelope: :ok_hand: applied mute to @waxen zodiac until <t:1639803477:f> (59 minutes and 59 seconds).
Ayeeee less gooo for the mods
ikr
!mute 544202101522432012
:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1639803508:f> (59 minutes and 59 seconds).
Wait whats inv?
"investigating"
invoice
ohh ok
i charge $1,000 per mute
from discord.ext import commands
import os
class TestCog(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@commands.is_owner()
async def reload(self, ctx, cog: str):
try:
self.bot.unload_extention(cog)
self.bot.load_extention(cog)
except Exception as e:
await ctx.send("Could not reload cog")
return
await ctx.send("Cog reloaded")
def setup(client):
client.add_cog(TestCog(client))
print(f"Background is loaded")``` is this right?
tho
do you accept loans?
12.5% APR
Off-topic channels
There are three off-topic channels:
• #ot2-never-nester’s-nightmare
• #ot1-perplexing-regexing
• #ot0-psvm’s-eternal-disapproval
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
🧍♂️
good one. i'll leave you guys to it
thanks again
isnt their something to reload a cog?
i think it was self.bot.reload_extention(cog)
it unloads and loads a cog if irrc
Well do you know whats the code for loads and unloads?
why?
!d discord.ext.commands.Bot.reload_extension
reload_extension(name, *, package=None)```
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.unload_extension "discord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension") except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
how do i get the bot's integration role
Nvm
the bot isnt responding to my command
@commands.is_owner()
async def reload(self, ctx, cog: str):
try:
self.bot.reload_extention(cog)
except Exception as e:
await ctx.send("Could not reload cog")
return
await ctx.send("Cog reloaded")```
any errors
show the class
discord.ext.commands.errors.CommandNotFound: Command "reload" is not found```
from discord.ext import commands
import os
class TestCog(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@commands.is_owner()
async def reload(self, ctx, cog: str):
try:
self.bot.reload_extention(cog)
except Exception as e:
await ctx.send("Could not reload cog")
return
await ctx.send("Cog reloaded")
def setup(client):
client.add_cog(TestCog(client))
print(f"Background is loaded")```
its not indented well
!d discord.Guild.self_role
property self_role: Optional[discord.role.Role]```
Gets the role associated with this client’s user, if any.
New in version 1.6.
they should be indented by 4 spaces
oh thanks
also
embed.add_field(name="Description", value=[cog.description if cog.description else "No description provided."], inline=False)
```im using this for so it takes the cog's description if there is one, else it'll be "No description provided", for some reason this is the output:
yes
use () instead of []
Or use an or expression
!e ```py
description = "test"
print(description or "default")
description = None
print(description or "default")
@west escarp :white_check_mark: Your eval job has completed with return code 0.
001 | test
002 | default
should look like this
class TestCog(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@commands.is_owner()
async def reload(self, ctx, cog: str):
try:
self.client.reload_extention(cog)
except Exception as e:
await ctx.send("Could not reload cog")
return
await ctx.send("Cog reloaded")
def setup(client):
client.add_cog(TestCog(client))
print(f"Background is loaded")
shouldn't it be self.client.reload.... inside the command?
And the setup outside the class
well yes but im to lazy🧍♂️
done happy?
not yet
to bad
how'd i convert the member.created_at datatime value to how long ago it was?
subtract it from datetime.now() to get a timedelta object , it will tell how long ago it was
okay ill try it
oh tysm
TypeError: can't subtract offset-naive and offset-aware datetimes
also is it possible for me to override the global command error handler
just like i thought lol
cuz for commands.MissingRequiredArgument, in the global handler it'll do ctx.send_help(ctx.command) but for a specific command i dont want that to happen
iirc, you can just do @command.error
Decorate a method which you use to handle it
Can just pass to ignore
thanks
Oh , you're using 2.x+ , convert member.created_at to an offset aware datetime object
Or just use a Unix timestamp tbh
kakashi/cogs/info.py line 107
'Joined Server' : f"{member.joined_at.strftime('%d %B %Y')}` <t:{int(member.joined_at.timestamp())}:R> `{position+1}/{ctx.guild.member_count}",```
Problem?
yeah that's better
Do u know u can also do utils.format_dt()?
With time.time() returning the current unix time
no error code
So Im trying to make a simple thing that makes the bot greet you when you say "hello" and its name. As of right now.. I have this
if msgl.startswith('hello chimera') or msgl.startswith('hi chimera'):
channel = message.channel
await channel.send('Hello! What is your name?')
print('Check 1')
def check(m):
return m.content == 'hello' and m.channel == channel
print('Nice')
msg = await client.wait_for('message', check=check)
await channel.send(f'Hello {msg}!')
print('Check 2')
``` Naturally the prints are to see exactly where its going wrong. It printed both "Check 1" and "Nice" but not "Check 2".. what am I doing wrong?
Oh, that's pretty much of old code from 1.7 , was it added in v2 ?
Show code...
Yups. Iirc it takes a datetime object
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.9)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
Tho it takes a datetime object, in disnake, we modified it to take in an int too
oh I see , I'll update it later 
I asked for code.....
Not a code problem
from discord.ext import commands
class TestCog(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@commands.is_owner()
async def reload(self, ctx, cog: str):
try:
self.client.reload_extention(cog)
except Exception as e:
await ctx.send("Could not reload cog")
return
await ctx.send("Cog reloaded")
print(f"Reloaded")
def setup(client):
client.add_cog(TestCog(client))
print(f"Background is loaded")```
this is my cogs file
You could just do😭
@client.event
async def on_message(message):
if message.content.startswith("hello"):
await message.channel.send(f"hello {message.author.mention}")
He selected the option Run as Python Module
You setup function is inside the class
for filename in os.listdir(path='.'):
if filename.endswith("Cogs1.py"):
client.load_extension(f"Cogs.{filename[:-3]}")
Move it outside
I could, but Im trying to learn wait_for
Ah i see pretty easy
I hope so, I feel like it could be useful in the future
Yea cool , now run the main file
It really is btw
Except Im already failing bc it aint working 

https://media.discordapp.net/attachments/343944376055103488/920897738596560946/unknown.png
And run it from here ffs
Is wait for a coro?
Cant remember 
yes
Ok
too many mistakes lmao check the docs
why is it named wait_for then 
Bruh
He was just asking if u await it or not
view.wait() isnt a coro
it isn't?
No
!d discord.ui.View.wait
await wait()```
Waits until the view has finished interacting.
A view is considered finished when [`stop()`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View.stop "discord.ui.View.stop") is called or it times out.
There (:
yea it makes no sense if it isn't a coro
Wait it is
await view.wait()
```
😭
I should go to sleep smh
nice
Had a massive brain fart so i should go to sleep
Wdym?
🚶 dude
Bro🕴️
your brain farded
Yes
👀
scroll up..
🕴️ wdym im not
Yes you are you imposter 🕴️
😃 don't know 🕴️
🕴️
🕴️ best emoji
C:\Users\thoma\AppData\Local\Programs\Python\Python310\python.exe: No module named enter-your-module-name
it keeps saying this
Yeah but dont steal it from me smh
is enter-your-module-name defined?
smg
😳
well its saying this from my main python file
Was a typo
I told Gangster his problem but okay
dude, you know basic python, modules can only be imported if they exist
☠️
🕴️
🕴️
@jade tartan just do python main.py or whatever your bot file name id
🕴️
my man it's a module not found error 😂 idk whats the module
🕴️
i once got a ssl certificate error for calling commands.Bot() twice 🕴️ ☠️
Im always lurking
never showed the issue itself
🕴️
You know... I know what I am doing, soo I think u should just wait (:
well it isnt that it does that when i come and run the code
thats what the file directory writes at like that
ok but what is the module name?
☠️
ama just uninstall python
ok where's da issue now
and vs
wait you didn't know basic python from the start 🕴️
no i know
then why uninstall python
I was born knowing py
python never gets old
Kinda does😔
if there was a extension in vscode where if you had an error it would give you a stack overflow link that'd be awesome
peak level of laziness
Make it yourself
We know you would use it
lie of the day
i'd use it tho ☠️
I wouldn't cuz im to good🕴️
i wouldn't use stack overflow for forgetting a bracket 💀
go to #ot0-psvm’s-eternal-disapproval before we get killed
Trust
Lol
Hello, could anyone take a look at this and tell me what I'm doing wrong?
import discord,os
from keep_alive import keep_alive
from discord.ext import tasks
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
global members
guild = client.get_guild(757463397683036200)
role = guild.get_role(793942123627282452)
members = [member for member in guild.members if role in member.roles]
@tasks.loop(seconds=120)
async def check_role():
global members
guild = client.get_guild(757463397683036200)
role = guild.get_role(793942123627282452)
members = [member for member in guild.members if role in member.roles]
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!scosa'):
try:
await message.channel.send(os.getenv('VerifiedBMHour') + ' +9 in 30 minutes hosted by ' + os.getenv('scosa') + '!')
except:
await message.channel.send('Only Admins have permission to use this command.')
return
The command works, but it's not locked behind the role it should be, and I have no idea why
import os
they did
true
dont use discord.Client for making commands
use commands.Bot()
!d discord.ext.commands.has_role you can use this to check if member has role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
if you use the Bot commands constructor
Also start the task with task.start()
your weird sometimes
Sometimes?
doing what sarthak said would still be better and cleaner
why when the bot switches to 2 if it gives such an error?
msg_1 = await ctx.send(
embed = discord.Embed(title = 'Выбирите язык\nSelect language', timestamp = ctx.message.created_at),
components = [
[Button(style = ButtonStyle.blue, label = 'Русский'),
Button(style = ButtonStyle.blue, label = 'English')]
])
responce = await bot.wait_for('button_click', check = lambda message: message.author == ctx.author)
if responce.component.label == 'Русский':
msg2 = await msg_1.edit(
embed = discord.Embed(title = '2', timestamp = ctx.message.created_at),
components = [
[Button(style = ButtonStyle.blue, label = 'Русский'),
Button(style = ButtonStyle.blue, label = 'English')]
])
Is the embed changing?
Yes
Hmm, Interesting
the stuff you want to do works right?
yes
it happens because interaction is not responded when you click the button
you can just make an ephermeal response sayin button is clicked or something to avoid it
I didn't understand how.
help?
looks like you have to defer it
Myxi you havent been here in a while hows it going
i used to get that kind of error later when i deferred it, it workef fine
pretty well
Thats nice
how bout you
Better 
i made some crap api wrapper
What api?
what do you mean?
idk, use a good fork like disnake, it could be just an issue with whatever you're using
maybe they're handling it wrong
or outdated
we use defer when it will take more than 3 seconds to respond
however in your case it doesn't seem to take more than 3 seconds
why do you write with riddles?
if all you want are ui elements except application commands, use discord.py 2.0
