#discord-bots
1 messages · Page 1088 of 1
[40;38;2;255;255;0mHello
If your gonna be sending the codeblock through the bot though, using \u001b would work
If your sending the codeblock through yourself, you'd have to use the actual character
bot raids?
i think he means people botting his server
needs to be in an ansi codeblock
im dumb eys lol
just realised
```ansi
text
```
i was gonna tell you about the slash lmao
guess im too slow 😔
https://github.com/an-dyy/Rin/blob/master/rin/models/builders/ansi.py ANSI code block builder I made for my API wrapper
You can copy paste & use it
stop flexin
If you want to, it's just much easier
nice idea andy 😳
how do i send a DM to a user in an async function that is not a command?
https://github.com/an-dyy/Rin/blob/70066f04157a20a08cfe65ce9235ce65d35f8be3/examples/components/button.py#L1-L52 looks good too
use get_user to get the user, and use .send() method on it
my API wrapper
you mean** our** api wrapper
no
i already tried that
it doesn't work
it only works inside a command
you are missing member intents.
no sir i have it
Looking at your contribution, the only did you added was the discord widget to the README
use fetch then...
wdym

no i actually corrected the installation url
i did allot
!d discord.Client.fetch_user
await fetch_user(user_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
Note
This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_user "discord.Client.get_user") instead.
Changed in version 2.0: `user_id` parameter is now positional-only.
bruh the error is created in the line that sendds the message
Okimii did some useless PR while sarth actually did something
so that doesn't help
What error?
and member cache enabled,
do they even allow disabling it?
appreciate my work smh
so when i try to send a DM to a user outside of a command function, i get this error Timeout context manager should be used inside a task but when i send it in a command it works
i really wanted to use rin but the developer is too lazy to get the library done
Can you send your code?
absolutely
async def onVote(userid):
def isUserAvailable():
return int(userid) not in farmusers
condition = asyncio.Condition()
await condition.wait_for(isUserAvailable)
user = bot.get_user(int(userid))
if user is not None:
await user.send('Thanks for voting!')
just commit to Nakano😏
how do i set the discord embed colour to a random one each time?
forget everything, just use ```py
await bot.http.send_message(user_id, "some cool stuff")
thanks ill try that
Wonder who that could be
!d discord.Color.random
!d discord.Colour.random
classmethod random(*, seed=None)```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") with a random hue.
Note
The random algorithm works by choosing a colour with a random hue but with maxed out saturation and value.
New in version 1.6.
remember color is an alias
totally not sir andy
@slate swan that line doesn't work File "", line 13, in onVote TypeError: HTTPClient.send_message() takes 2 positional arguments but 3 were given
can i see the code you used
yeah
this is my modified code
async def onVote(userid):
def isUserAvailable():
return int(userid) not in farmusers
condition = asyncio.Condition()
await condition.wait_for(isUserAvailable)
await bot.http.send_message(int(userid), "Thanks for voting!!")
color = discord.Colour.random()
anything wrong with this python await bot.http.send_message(int(userid), "Thanks for voting!!")
the last parameter is unexpected
what's your bot variable? is it already running?
yeah, you should be sending messages to users with the User or Member objects. You shouldn't need to go to the http clients methods
could you send the full error message?
i cant because it is outside a command
ok
yes you can, with get_user and fetch_user
that aint working for them for some reason
Well that's why I'm asking to see the error
File "", line 13, in onVote TypeError: HTTPClient.send_message() got an unexpected keyword argument 'content'
I meant the error you were getting before, with your original code
oh ok
what dpy version are you on? they made changes in 1.7.3 and 2.0's httpclient
2.0
File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/aiohttp/helpers.py", line 635, in __enter__ raise RuntimeError( RuntimeError: Timeout context manager should be used inside a task
And the rest of the traceback?
wait did you just start the task before bot.run ?
Traceback (most recent call last): File "/Users/yourmom/Documents/discordbot/bot.py", line 276, in dblvote asyncio.run(onVote(842981557283323914)) File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/asyncio/runners.py", line 44, in run return loop.run_until_complete(main) File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/asyncio/base_events.py", line 641, in run_until_complete return future.result() File "", line 28, in onVote File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/discord/abc.py", line 1493, in send channel = await self._get_channel() File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/discord/user.py", line 454, in _get_channel ch = await self.create_dm() File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/discord/user.py", line 496, in create_dm data: DMChannelPayload = await state.http.start_private_message(self.id) File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/discord/http.py", line 441, in request async with self.__session.request(method, url, **kwargs) as response: File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/aiohttp/client.py", line 1117, in __aenter__ self._resp = await self._coro File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/aiohttp/client.py", line 448, in _request with timer: File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/aiohttp/helpers.py", line 635, in __enter__ raise RuntimeError( RuntimeError: Timeout context manager should be used inside a task
what task
wots this?
?
how is this function invoked?
Are you calling it before calling bot.run?
thats the issue, you bot is not even running and youre trying to use get_user and fetch_user
no
the error is not on get_user read the traceback
I never expected bot verification to be that tough
channel = await self._get_channel() File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/discord/user.py", line 454, in _get_channel ch = await self.create_dm() File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/discord/user.py", line 496, in create_dm data: DMChannelPayload = await state.http.start_private_message(self.id)
``` targets to creating a dm with an invalid user
That's not what the error means

how do i edit an embed
await msg.edit(embed=embed)
@elfin moon Try running the task using the bot's loop```py
bot.loop.run_until_complete(onVote(842981557283323914))
its not working
How to get the most recent message of a channel in discord.py?
Show code
any example?
channel.last_message :)
in an actual command instance I meant
@bot.command()
async def my_command(ctx: commands.Context):
last_message = ctx.channel.last_message
await ctx.send(f"Last message: {last_message.content}")
How to install jikashu?i installed it yet
you need to await the client.load_extension
use the setup_hook to load extensions!
Ahh got that
!d discord.ext.commands.Bot.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for "discord.ext.commands.Bot.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready "discord.ext.commands.Bot.wait_until_ready")...
from z.keep_alive import *
keep_alive()
i tried putting print('im aliveeeeeeeee') after keep_alive() but its not printed
its rate limited
just wait
to prevent api abuse i think
but its normal to get rate limited
i said its normal right? 🤣
:/ am i being rude
=.= visible confusion
whatever
sry ig
not quite sure how you're trying to help
obviously im not a pro, thats why im asking here
idk why this doesn't work
member = message.author
role = discord.utils.get(message.guild.roles, name = "test")
member.add_role(role)
Await it

If you're getting rate limited on a daily basis then you're making too much requests simply
simple: don't use replit
or dont spam stuff
i see the params for discord.Guild are *, data and state. i cant find what they represent in the documentation. im not sure how to simply get a member list from it either? anyone can give some pointers?
all you can do is wait, and man update the python version in the container, you're literally using 3.6
im guessing i need to use a for loop to get individual items in discord.Guild.members? if i try to print(members_list) which stores the discord.guild.members, i get some memory adress. ive been in the documentations all day, i think im starting to see double lol
it should be an instance of discord.Guild, not the class itself
like this?
members_list = discord.Guild()
print(members_list.members)
You're not supposed to manually create it
Hence why it's not documented
Usually a guild instance will be provided for you can call .members on it
yeha it could be that im totally not using the proper way to do what i want to do
@bot.command()
async def print_members(ctx: commands.Context):
print(ctx.guild.members)
Is one example
im trying to check if the members in the discord have the ActivityType "streaming" and if they do, assign them the role LIVE
but i cant find much about it, and i guess im getting tired too loll
You'll wanna use the on_member_update I believe the name is
the most common ways of getting a guild object would be py context.guild if you have a Context
message.guild``` if you have a Message object ```py
bot.get_guild(server id)
``` if you have the server Id
For your use case you don't need the guild at all
!d discord.on_member_update see this event
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change...
You can check if the after has a new activity with "streaming"
nice, thanks a lot Robin!
My pleasure, feel free to ping me or ask here again for further assistance
whats the equivalent of discord.TextChannel in lightbulb
hikari.GuildTextChannel
consider lightbulb as nothing more than the discord.ext.commands, its just a command handler
all the api related classes are provided by hikari
ctx.channel_id for the id
ctx.get_channel() for the channel
tyvm :)
ok i think Robin was unto something. the streaming ID is different for every server or it's the same?
wait it's role id, sry
i found snippets of code written for discord.js .. not quite sure how to translate to python
this is not working
role ID is different for each server I believe
The hardest part is probably figuring out if a user has started streaming on_member_update, giving the role is easy peasy
this is the part i think, but it's js
const updatedMember = await newMember.member.fetch();
await addRemoveStreamRole(updatedMember, !!updatedMember.presence.activities.find(a => a.type == "STREAMING"));
theres lots of commented stuff, im trying to retro engineer the thing with my very limited knowledge lol
found the intents thing and updated my bot instance with intents=intents
intents = discord.Intents.default()
intents.members = True
stream = discord.utils.get(member.activties, type=discord.ActivityType.streaming)
if stream:
await member.add_roles(streamer_role)
hmm looks like member not defined. not sure how or where to use your code. thanks for helping
So I have a command with await winner.create_dm()
But if it fails to create the dm
My whole bot goes unresponsive
can you wrap it in a try except block
Im having trouble with my bot assigning a new role once i have it removing all roles from user → using it for a quarantine type bot
for role in member.roles:
if role.id in EXCLUDED_ROLES:
return
if config.QUARANTINE_ROLE not in member.roles:
for word in res:
if word[0].upper() in str(member.activities).upper():
for role in member.roles:
if role.name != "@everyone":
await member.remove_roles(role),
await member.add_roles(role.id(QUARANTINE_ROLE))
embed = discord.Embed(color=0xFF0000)
embed.description = f"{member.mention} got quarantined because of word `{word[0]}` in his status!"
await bot.get_channel(config.ANNOUNCEMENT).send(embed=embed)
return
im stumped at what to do, this is making me very stressed trying to find a solution haha
you mean ctx.channel.id
i found this for roles
https://discordpy.readthedocs.io/en/latest/api.html#discord.on_presence_update
huh

why are you doing that? it isn't necessary really
you can simply await winner.send() to send them a message
with a try except which catches discord.Forbidden probably
indeed!
i wish there was a way to check if a user has its dms open without actually dming them
don't think that would be possible
cz an endpoint for checking dm statuses seems weird
eh why an endpoint, it could just be a part of user's payload like .bot is, but again privacy issues
hm yeah, was thinking about the same but it won't really be a good idea even if it wasnt about privacy issues
who knows if sm1 had blocked only your bot specifically and the dms are open for others
totally not me and mee6
just close your dms from the privacy settings 😔
can i have text centre aligned in an embed description?
unless you manually space it up, naw
spaces should work too
\u200b moment
- remove the
eventdecorator - use an instance of
Guild, then do.memberson it.. the thing you have right now will raise an exception - I forgot
how do i type hint an option, while invoking a command i type #discord-bots i want it to get the channel object and not a str
thanks i moved to presence update, but im still failing lol
that will just get you a single space, its technically not possible to do what you're trying to, i mean try doing it in ur client ....
you mean IDE?
hikari.TextableGuildChannel, you can mention channel_types too
cause GuildCategoryChannel are considered as TextableGuildChannel too
on your discord...
so i have to convert it manually in the command?
not sure what you mean
nope, py @lightbulb.option( "channel", "Select channel", hikari.TextableGuildChannel, required=True, channel_types=[hikari.ChannelType.GUILD_TEXT] )
the 3rd argument in the options decorator is the type of the option
like this
Hello everyone. I am having an issues with client.fetch_guild() that I'm hoping someone can help.
I have a cog with the following code in a command:
guild = await self.client.fetch_guild(guild_id)
print(len(guild.members))
async for member in guild.fetch_members():
print(member.name)```
the first print, prints 0 and the iterator prints nothing. Does anyone have any ideas why I can not seem to retrieve the members?
I do have my presences set
```python
intents = discord.Intents.default()
intents.members=True
intents.reactions=True
intents.guilds=True
intents.presences=True
client = commands.Bot(command_prefix= PREFIX, intents=intents)```
ya right, just notices the type param
im trying to translate discord.js to discord.py
client.on('presenceUpdate', async (oldMember, newMember) => {
// const guild = newMember.guild;
// const streamingRole = guild.roles.fetch("972677238766063717");
const updatedMember = await newMember.member.fetch();
if(newMember.activities.find(a => a.type == "STREAMING")) {
if(!updatedMember.roles.cache.has("972677238766063717")) {
console.log("Adding streaming role to " + updatedMember.user.username)
updatedMember.roles.add("972677238766063717");
}
}
else {
if(updatedMember.roles.cache.has("972677238766063717")) {
console.log("Removing streaming role to " + updatedMember.user.username)
updatedMember.roles.remove("972677238766063717");
}
}
} );
try typing what you are trying to send on discord...
if a message has 5 reactions, sum(single_reaction.count -1 for single_reaction in all_reactions) would be equal to len(reaction.message.reactions) -5 right?
@loop(seconds=90)
async def set_live_role(oldMember, newMember):
discord. # not sure how to implement the on_presence_update(before, after)
updatedMember = await newMember.member.fetch()
if newMember.activities.find("STREAMING"):
if not updatedMember.roles.cache.has(LIVE_ROLE_ID):
updatedMember.roles.add(LIVE_ROLE_ID)
else:
if updatedMember.roles.cache.has(LIVE_ROLE_ID):
updatedMember.roles.remove(LIVE_ROLE_ID)
dont tell me you just used some js to py converter for this
no, thats just me trying to make it work. been at it all day. its the only feature left to add to my bot that doesnt work lol
It's js
I haven't used listeners before but could you do something along the lines of listening for a members activity change and pass in the before activity and after activity?
i think thats what im trying to do
It's the person to whom the role is to be added
its checking for activityType "streaming" i think
Yes
Yeah I don't know how that works in discord py. If someone knows they can elaborate. Otherwise you could brute force it and keep a dict or lists of tuples or something of all the people in the discord based on their id. Check everyones activity every 90 seconds and if they are streaming add the role and add it to the dict. If they already have the role, ignore it. If they have the role and are not streaming, remove the role and dict entry
Firstly, do you know the basics of python?
ive been trying to do something similar. im just not that great with the documentation
the only example i have working is with djs, so it complicates stuff.. i have no clue how to translate to python
Why do you wanna translate to python?
are you using cogs or not?
im guessing not. not sure if it's needed too
cause it's a python file
You would know if you were. Eventually you probably want to learn how, but not necessary if you are just making a bot for yourself or just a small server or something
That's not what I meant, why do you wanna use python for your bot and not js?
im already connected to discord api and twitch api, using it to post to discord and stuff. this is my last "feature" that i want
why would i want to use js? im not sure i follow what you're asking
yeah, im learning python. i dont have time to learn 2 language at once. one baby step after the other lol XD
Also, bump on this. If anyone could help I am losing my mind over this.
is there another way im meant to do this? im trying to see if a user left because they were kicked
um.. anoyne here ?
yeah
trying to get you some code to work with btw
whats your error
your bots ratelimited
is it coz im using nextcord ?
¯_(ツ)_/¯
The error is that the guild returned has no members in it's members attribute and guild.fetch_members() also returns no members
how am i supposed to make it right then?
for member in guild.members
idk, you cant unratelimit a bot
guild.members has a length of 0
thats an automatic thing, it takes 1h to 3 days @spare urchin
how may i know ?
uhm...ok...
try other guilds, maybe its a server error
why dont you just use intents=discord.Intents.All()
you use discord.py?
yes
well i dont understand a shit from its docs...
I have. If I pass any of the guilds in using context. ctx.guild.members has all the members, but if I pass in buy guild id and do the fetch_guild the guild that is returned has the right name and id and stuff, but no members
are you fetching the guild or getting the guild
theyre two different things
x = await self.bot.fetch_guild(id) makes an api call
x = self.bot.get_guild(id) doesnt make an api call, and is not awaited
guild = await self.client.fetch_guild(guild_id)
Let me try the get_guild and see what happens
try with guild = self.client.get_guild(guild_id)
Maybe since it is an api call, it isn't passing the proper intent along with it for some reason
¯_(ツ)_/¯
and faster
thats kinda invalid, python is slower at most of the points
python can be the fastest lang, imo
slower to run maybe, but faster to code and/or learn i agree
indeed
thats a heavy cap
if used correctly, you can have things executed almost double the speed as opposed to improper implementation
alright im not gonna solve my problem tonight. time to get some sleep. good night all.
but thats straying from the topic, being discord.py
yes, you would be using the master branch of discord.py for that
pip install -U git+https://github.com/Rapptz/discord.py
and use the discord.ui.View class, install the library and ping me, ill help you out
whats the issue
try doing the same in c in the worst way possible, it will still be faster
i guess 😂
found some code from djs.. trying to translate it to dpy. simply put, i want to check for members in the discord when they get the streaming activity, and give them LIVE role. drop live role when not "streaming"
!d discord.on_presence_update
discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") updates their presence.
This is called when one or more of the following things change:
• status
• activity
This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences "discord.Intents.presences") and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled...
ive got something just for that, wait here
hi does it matter like
@commands.has_any()
@commands.command(name="@E")
can i put the commands.has_any()
up or down of @commands.command() with my choice if no where should i put it
@round knoll so check if before.activity != after.activity and something
i cant make that work. idk why. the syntax shown in the documents just dont work. idk how to write it
what do you currently have
@heavy folio
dont ping for help
i think you actually need a check in check_any
and it doesnt matter position since its a decorator
bruh it was an example
alr thanks
i tried to just translate the djs file i found to dpy lol
# checks if discord activity is streaming, if true, assign LIVE role, if Flase, remove LIVE role
LIVE_ROLE_ID = 972677238766063717
@loop(seconds=90)
async def set_live_role(oldMember, newMember):
discord.on_presence_update(oldMember, newMember)
updatedMember = await newMember.member.fetch()
if newMember.activities.find("STREAMING"):
if not updatedMember.roles.cache.has(LIVE_ROLE_ID):
updatedMember.roles.add(LIVE_ROLE_ID)
else:
if updatedMember.roles.cache.has(LIVE_ROLE_ID):
updatedMember.roles.remove(LIVE_ROLE_ID)
decorator positions do matter, not in this case
but they execute from bottom to top, not simultaneously all at once
okay
its clearly not the way to go. but ive been coding and using documentations all day and my brain is fried lol
act = f'{member.activity.type}'.replace("ActivityType.playing",
f"Playing {activity_name} {rich_presence}").replace(
"ActivityType.listening", f"Listening to {activity_name} {rich_presence}").replace(
"ActivityType.watching", f"Watching {activity_name} {rich_presence}").replace(
"ActivityType.streaming", f"Streaming {activity_name} {rich_presence}").replace(
"ActivityType.competing", f"Competing in {activity_name} {rich_presence}").replace(
"ActivityType.custom", f"{activity_name}")
@commands.Cog.listener()
async def on_member_update(self, member) -> None:
guild = self.bot.get_guild(your_server_id)
member = guild.get_member(member.id)
if discord.utils.find(lambda act: isinstance(act, discord.Streaming), member.activities):
if role in member.roles:
return
if role not in member.roles:
return await member.add_roles(your_role_id)
if not discord.utils.find(lambda act: isinstance(act, discord.Streaming), member.activities):
if role in member.roles:
return await member.remove_roles(role_id)
if role not in member.roles:
return```
just wrote that up, should be good
i dont think it would be approriate to share the 150 lines of codes in here tho?
@round knoll i updated the code, that should work
good code dude, well; sort of. i know youre new to python, but the usage of if not value instead of if value == (None or False): is astonishing, i love seeing it especially from beginners. its very tedious dealing with people who dont actually know the trivial attributes of Python, so i personally thank you for taking the time to learn. in return, enjoy the spoonfeeding i just pasted above
tip: else: if ...: should be elif ...
wtf 😂
actually now that I think of it there is no need to check anyway because I completely forgot you can see their activity so easily
🚶♂️ you guys are overdoing it
line 209, in wrapped
raise CommandInvokeError((exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: Replacement index 5 out of range for positional args tuple
@commands.command(aliases=['server'])
async def servers(self,ctx):
if ctx.author.id in OWNERS:
servers = self.bot.guilds
servers.sort(key=lambda x: x.member_count, reverse=True)
await ctx.send('***Top servers with Bot:***')
for x in servers[:50]:
await ctx.send('**{}**, **{}** Members, {} region, Owned by <@{}>, Created at {}\n{}'.format(x.name, x.member_count, x.owner_id,x.created_at,x.icon.url))
y = 0
for x in self.bot.guilds:
y += x.member_count
await ctx.send('**Total Bot users:** ***{}***!\n**Number of servers:** ***{}***!'.format(y, len(self.bot.guilds)))
can someone help
Hello, I currently have this: https://paste.pythondiscord.com/hezuvetutu
Where it has if question1.content == '': and else.
The else check only works once, how could I make it persist until question1.content == '':?
ive never actually read the documentation for python, everything i know i know because i literally trialed every error before getting to my result, hence why my error handling is so profound (as seen in the code block i sent earlier)
youre indexing too far
question Terror, does that function needs to be wrapped into a loop of 90 seconds? im not sure how it works
async def event(before, after):
if any(a for a in after.activities if a.type == discord.ActivityType.streaming) :
if not <check if user has role>:
# add role
else:
# dont do stuff
``` is basically what you need.
!d any
any(iterable)```
Return `True` if any element of the *iterable* is true. If the iterable is empty, return `False`. Equivalent to:
```py
def any(iterable):
for element in iterable:
if element:
return True
return False
it works when a member updates their status
this is quite helpful.
thats when the functions called
oh cool
ever hardcode a status displayment userinfo command?
how do i fix it ?
change your index method, id say add the objects to a list after a condition
x = []
if len(x) <= 50:
x.append(your info)
nope, I don't usually hardcode anything until really needed
me on the other hand
get_guild worked by the way. Thank you very much
np
also the python speed thingy
c++ => ```cpp
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 100; i++)
{
cout << i << "\n";
};
}```
for i in range(100):
print(i)
``` a diff of 0.02 seconds in execution
🙈
now lets see if anyone can solve my problem
im going to have a fucking aneurysm
ive been trying to figure this out all day, and nothing works.
@commands.Cog.listener
async def on_member_remove(self, member):
queue = [i async for i in guild.audit_logs(after=datetime.datetime.now() - datetime.timedelta(seconds=5), action=discord.AuditLogAction.kick)]
if queue:
member = queue[0].user
#do something to member
``` WHY does the `after` kwarg do nothing??!?!? i kicked a member 3 hours ago, and when a member leaves it still bans the person who kicked the member. Essentially i need to check if a member left because they were kicked
also, turns out the after kwarg is implied in the discord api documentation, its just been flagging errors since 2017 so discord decided to just not fix it
I mean that's expected from discord, sooo
Ah, hi there! Yup, long time indeed
i uhhhh got into some super coding
Nice, but actually that's a feature in a few bots in dpy server
some really esoteric shit if u ask me
Cool!
yeah, its spreading 😓
what've you been up to? any dpy breakthroughs?
Nah I have kinda took a hiatus from coding
awh
Yea, personal issues haha
so does anyone know?!
i think its related to timezones...
are you running the bot somewhere else and not on your local device?
and its commands.Cog.listener()
Prolly that's the issue
that should not run at all then 
doesn't after take a func
and when a member leaves it still bans the person who kicked the member
they probably just missed it while sending it or maybe idk
maybe
that's the case in some other methods
!d discord.Guild.audit_logs
async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the guild’s audit logs.
You must have the [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") permission to use this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
```...
and thats what they r using
@slate swan
If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
this warning
after 5 seconds before
imma make a pr to discord.py correcting a UTC to an UTC kek
a UTC is correct
it's youteesee
discord api bug, the after kwarg hasnt worked in 5 years cuz discord wont fix a simple bug
right, meh's smort
is it? i always thought its Universal Time Coordinated
lemme change the name real quick
@slate swan hmm, i went for a test live and the bot did not assign the LIVE role. it did post to my discord tho! which was one of the feature. !ping and !hello works too
it is correct, read meh's msg
make it extra smol
tf, english is weird
nah
lots of yellow highlights, not sure if normal.
yo wanna give me that code lmao
yeah, i wrote it on the fly. lots of stuff there isnt defined
700 line cog, ill send it to you for $75USD PayPal (with code comments to explain how it works)
lol
wait - i think its against the rules to say that 😓
yep
lemme revise
10 lines code, for free
ummmm it just says dont offer or ask for paid work, im just stating a price so idk
if something thats only 700 lines is worth $75 my bot is worth hundreds
i dont think it's about the number of lines tho..
your bot doesnt log months of user data and construct a pie chart showing how long they spent online (screentime)
im stuck in termux
or tell you which commands are favoured by usrrs
how do i import code??!?
i could sell you 5000 lines of print("Hello world!") for 1k lol
or what their past usernames are :P
i could easy add that to mine
and i already have that
my bots simply dont run, they are just open sourced examples lying on my github
not a bad idea actually
from file import Class as MyClass
full import string, youll never really need more than that. you get the gist of it
def not hardcoded
😭 not that
mmm
out of all your bots, whats the biggest one (linecount wise)
your bots. not Dyno
TypeError: str is not an int: "Dyno"
idk , all of the extensions are like 150-400 lines
ret = await coro(*args, **kwargs)
File "/home/runner/mv/cogs/utility.py", line 81, in channelinfo
embed.set_footer(text=("Created on {} ({} days ago)".format(channel.created_at.strftime("%d %b %Y %H:%M") (ctx.message.created_at - channel.created_at).days)))
TypeError: 'str' object is not callable
embed.set_footer(text=("Created on {} ({} days ago)".format(channel.created_at.strftime("%d %b %Y %H:%M") (ctx.message.created_at - channel.created_at).days)))
why is this wrong
3,662
11737, my bots line counts (accounts for every bot file, excluding files that dont end in .py and files that stray from bot specific files (cogs, utils ect)
Lol I only have one single bot which I'm rewriting since months now
ive made a second bot, started last week
well, 😔 its running and people use it LMAO
Hardly*
a very fine anti nuke, actually. up to 1.2k lines now i think, week 2 😋
Won't be surprised if I take it down after a few weeks
Ngl I'm bored of discord bots. I wanna focus on other projects but can't gather enough motivation
i remember using it just to get replies to uwu messages
Nice, u making the bot answer to uwu
At least it's not like it's owner
i'd never get bored with discord bots cause i never completed a bot 
you cant ever complete a discord bot
Same, never completed a single project
im done with 6-7 commands, and boom a rewrite in another library
and if you think youve completed a discord bot, you just need to process more ideas
youre never done, not with these projects
why don't i ever get any message content from this bruuuu
ignore that its replit i needed to share it with someone
ill re-frame the sentence
i never made the bot reach to a usable state
yikes
message content intent
damn mine has like 60
could anyone help
im up to 140 commands 😐
noice
bru look at the intents
and about 20 unique features
Sorry, my bad
i wanna say.... 20 cogs?
why "😐"
unique. describe them pls
this is a prime example
uh thats 1 command
yes, a prime example
he said describe them
not discord.py/fork either
ill just screenshot my bots changelogs which have not been updated in almost a month (i think, i have horrible time tracking skills)
Can anyone help me out
whats with the "😐" tho
I just shifted from js to python
Wrong token
you put "token" as the token
@slate swan
so role would be "LIVE" or the role id? im confused
thats only 15
also where is act used
noice commands... i just made a bot which record stats for another bot this week :p
how many guilds is it in
100, pending verification
does anyone have ideas about this tho like wth
mm then wait for his reply and see if it differs 🙂
wat
its been in 100 servers for over 3 months now
discord likes to take their fucking time with verification
ive sent 4 emails requests.
alright i just need to fix those undefined variables
seen this design so many times across diff people, definitely copied
rippp
when i sent that code, read below. shorter code was sent, just use that
whats copied
oh, my userinfo command?
i made that file back in August...
"whats copied" you can tell 100% that it was copied from that because if it wasnt he would try to defend it instead of just dodging
what aspect of it is copied
no offence but ive seen the same design before, many times in this server
like the whole thing
here? id love to see
Send more and it's gonna take more time
with the amount of data discord provides, a userinfo command would be really limited and almost same for all bots. so cant really frame something as a copy
U get pushed to a lower position in queue when u send a new email
Yea, I also learnt it the hard way
shorter code? from you or another user?
@maiden fable do u know how to use termux?
Never used it sorry
...ok
embed.add_field(name = "Created On", value = "{}".format(channel.created_at.strftime("%d %b %Y %H:%M")))
how to make the created on message like this <t:1624385691:R>
!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.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
or simply , <t:<timestamp>:R>
@slate swan that was yours right? the shorter code?
change event to on_member_presence_update , and your if statement for checking the role is wrong
Could someone help me in #help-chestnut, thanks
you can if not LIVE_ROLE_ID in member._roles:
hi sarth , have u ever used termux?
sadly not, but they def got noice docs on their wiki
you can check them out
i always get member not defined, is there something i should add somewhere. how do i grab the user and add_role(LIVE_ROLE_ID)
oo let me check
after._roles
after is your member object
how to use this for channel.created_at ?
int(channel.created_at.timestamp()) gives you the timestamp
ohk
I have reset the token then also
in the else: should i after.remove_role(LIVE_ROLE_ID) ?
kill 1 in sheell
after.remove_roles(discord.Object(id=LIVE_ROLE_ID))
LIVE_ROLE_ID = 972677238766063717
# checks if discord activity is streaming, if true, assign LIVE role, if Flase, remove LIVE role
async def on_member_presence_update(before, after):
if any(a for a in after.activities if a.type == discord.ActivityType.streaming):
if not LIVE_ROLE_ID in after._roles:
after.add_role(LIVE_ROLE_ID)
else:
after.remove_role(LIVE_ROLE_ID)
same thing for add_roles too
alright fixed
on_presence_update*
@round knoll correct what invalid-user said^
roger that, apparently, my id was wrong, even tho im sure i copy id from discord directly
retesting
sometimes that happens to me too
alright do i need a loop wrapper on this, or it updates when the user activity changes?
is there a way to force a check?
it automatically gets triggered when the activity changes
and yes there;s a forced way but dont use it 🙂
Please, could someone have a look at #help-chestnut, I have a really weird problem
ok, so to test this, i should manually give me the role, then stop the stream
it should remove it?
oh wait, do i wrap this on @bot.event
yessir
how can i check if a certain file currently exists within my project? and then display a different msg if it does?
ive setup saves in my game, and they are stored as json files that are identified by the players id who used the save command
and i want to bring up a warning/confirmation msg if someone tries to save who alrdy has a save file
but to do that, i need to be able to check if that save file alrdy exists
you need to await the add_roles and remove_roles
does it get printed tho?
!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`.
you can get a list of filenames
how do I use Messageable.fetch_message? can someone give an example?
ctx.channel.fetch_message()
but that is TextChannel.fetch_message, no?
textchannel is derived from messageable
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
indeed.
TextChannel is a subclass of Messageable
working with pycord, is it possible to have one person send a command that gives them button options for approve and deny but only have members with a specific role click the button for them to work?
!d discord.Member.roles
property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.
These roles are sorted by their position in the role hierarchy.
still nothing
alright, i think it's enough for tonight, i dont think im gonna resolve this. altho i think were close
hey @round knoll you could also try a different approach like to add the role like ```py
if not member.get_role(LIVE_ROLE_ID):
await member.add_roles(member.guild.get_role(LIVE_ROLE_ID))
the function `get_role` is a method of the `discord.Member` class, allowing you to see if a member has a certain role. If they do, it will return that role instance. If they do not, it will return `None`.
discord.Object technically should be working, but at least in my experience I have noticed quite a few issues with it - so maybe just the long way for consistency
lemme tp again #bot-commands
@round knoll im just reviewing your comparison logic
# checks if discord activity is streaming, if true, assign LIVE role, if Flase, remove LIVE role
LIVE_ROLE_ID = 983061320133922846
@bot.event
async def on_presence_update(before, after):
if any(a for a in after.activities if a.type == discord.ActivityType.streaming):
if not after.get_role(LIVE_ROLE_ID):
await after.add_roles(after.guild.get_role(LIVE_ROLE_ID))
print("Giving LIVE Role")
else:
await after.remove_roles(after.guild.get_role(LIVE_ROLE_ID))
print("Removing LIVE Role")
i cant take credit for any of this. this is way over my paygrade
sarth helped a lot, and invalid-user too
okay i have one review suggestion if it doesn't work as is and this is it ```py
if any(isinstance(activity, discord.Streaming) for activity in after.activities):
...
I think you should be a-ok to give it a go @round knoll
do you have another on_presence_update?
this is a global event, so it would take precedence over a cog-specific one
@bot.event instead of commands.Cog.listener
i think the condition is correct, because if not the if statment, the else statement would get executed and should print, seems more like a trigger issue
if failing to remove a role that isn't there in the first place raises an HTTP exception it is possible the exception is getting handled elsewhere and absorbed - causing the print statement to not execute
update @round knoll?
@round knoll it that function by any chance placed below bot.run()?
negative, nothing still
i have this all the way at the bottom of my file
if __name__ == "__main__":
check_twitch_online_streamers.start()
bot.run(disctoken)
actually i got the issue, change on_presence_update to on_member_update
presence_update was added in 2.0
and they apparently have 1.7.3
@round knoll
and add a print in the first line of the function to make sure it got executed
who has 1.7.3?
everyone who installs discord.py using pip install discord.py
just do the change i mentioned above, and it should be fine
# checks if discord activity is streaming, if true, assign LIVE role, if Flase, remove LIVE role
LIVE_ROLE_ID = 983061320133922846
@bot.event
async def on_member_update(before, after):
print("Zeddy bot is checking for roles")
if any(a for a in after.activities if a.type == discord.ActivityType.streaming):
if not after.get_role(LIVE_ROLE_ID):
await after.add_roles(after.guild.get_role(LIVE_ROLE_ID))
print("Giving LIVE Role")
else:
await after.remove_roles(after.guild.get_role(LIVE_ROLE_ID))
print("Removing LIVE Role")
i think that any accept a statement before the for
!e
my_list = [1, 2, 3]
print(any(a==3 for a in my_list))
@placid skiff :white_check_mark: Your eval job has completed with return code 0.
True
yup it does
!e print(any(a for a in (1,2,3))) # don't really need to
@slate swan :white_check_mark: Your eval job has completed with return code 0.
True
yup but he checks the activity type
um did you made any change i didn't ask to?
if he does the statement as i did he could rip off the if in his any function
can i pip --update discord.py 2.0
2.0 is available only with git
yeah that after.get_role lol, change it back to if not LIVE_ROLE_ID in member._roles
ok
i got a removing LIVE role printed
lets check for Giving LIVE role print
Zeddy Bot#1618 connected to Discord.
Zeddy bot is checking for roles
Removing LIVE Role
Zeddy bot is checking for roles
Zeddy bot is checking for roles
Giving LIVE Role
ITS WORKING
woooooooooooow
thanks for your time and your patience sarth
bed time, well deserved

in pycord can i get the roles of whoever interacted with a button with interaction.user?
yep :)
can i do user.roles?
no, but you can interaction.guild.get_member(interaction.user.id). roles
basically, getting a Member from the User object
i think interaction.user.id isn't working
isn't getting it since its returning None
Suggest more topics here!
yes
less pushy
dont force slash commands etc
dont send out annoying messages in DM
make verification 5 times easier
make heartbeat interval longer
allow self-bots
and on and on
Ppl are already using..
and they get banned 
hey, can someone help me, i don't know why but this little code break every other commands of the bot and idk why py @client.event async def on_message(ctx): if "jul" in ctx.content or "Jul" in ctx.content or "JuL" in ctx.content or "JUL" in ctx.content: await ctx.add_reaction('👽')
change client.event into client.listen()
tysm it's now working !
Good morning to you too ashley
heck
can discord bot know my discord time
discord time? elaborate
the time show when msg send side of the name
You can do it
I believe in you
!d discord.Message.timestamp
No documentation found for the requested symbol.
Look i'll make it more simple
you can read the vas an a
property created_at```
The message’s creation time in UTC.
ahyes, Tveriser
nvm, ill copy paste
Hahahahaha
Tvrsier
how does Dank Memer show time in embed footer 🤔
!d datetime.datetime.timestamp
datetime.timestamp()```
Return POSIX timestamp corresponding to the [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instance. The return value is a [`float`](https://docs.python.org/3/library/functions.html#float "float") similar to that returned by [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time").
Naive [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instances are assumed to represent local time and this method relies on the platform C `mktime()` function to perform the conversion. Since [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") supports wider range of values than `mktime()` on many platforms, this method may raise [`OverflowError`](https://docs.python.org/3/library/exceptions.html#OverflowError "OverflowError") for times far in the past or far in the future.
For aware [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instances, the return value is computed as:
```py
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
``` New in version 3.3.
Changed in version 3.6: The [`timestamp()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp "datetime.datetime.timestamp") method uses the [`fold`](https://docs.python.org/3/library/datetime.html#datetime.datetime.fold "datetime.datetime.fold") attribute to disambiguate the times during a repeated interval.
i got 2 problems in the below; how do i get the msgs to send in my discord channel when the command is set outside the main bulk of the code, and secondly does the os.path.exists look right, because it doesnt seem to work
@bot.command(name='save')
@commands.check(save_check)
async def command_save(ctx: commands.Context):
state = ctx.bot.game_states[str(ctx.channel.id)]
state_json = jsonpickle.encode(state)
if os.path.exists(rf'C:\Users\User\PycharmProjects\TRPG Bot\saves{str(ctx.author.id)}.json'):
await state.game_channel.send('Save file already exists. Do you wish to overwrite existing save? __(Yes/No)__\n'
'**Warning: This action cannot be undone.**'
)
state.valid_game_options = ['yes', 'no']
confirm_msg = await bot.wait_for('message', check=lambda m: m.content.lower() in ['yes', 'no'] and m.channel == state and m.author == ctx.author)
if confirm_msg.content.lower() == 'yes':
# put warning here about overriding saves
write_json(os.path.join('saves', f'{str(ctx.author.id)}.json'), state_json)
await asyncio.sleep(2)
await state.game_channel.send('Save Successful!')
elif confirm_msg.content.lower() == 'no':
await asyncio.sleep(2)
await state.game_channel.send('Save Cancelled. Game resumed...')
else:
write_json(os.path.join('saves', f'{str(ctx.author.id)}.json'), state_json)
await asyncio.sleep(2)
await state.discord.game_channel.send('Save Successful!')
actually its only the msgs i got problems sending rn
wdym outside the main bulk of code
an instance of the game is run within a func, while the bot.command is run outside of that instance
another thing i want to do is covert the above into a function and nestle it inside the instance so only someone actually playing the game can use the command
thats what im trying to do rn
if i can itll solve the msg send anyways
Can i see the block of code where the game is running?
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.
I have a problem with Youtube search python here is my code and the error
@bot.command()
@commands.guild_only()
async def play(ctx, *, mot_clé : str):
print(f"Play")
client = ctx.guild.voice_client
link = f'{mot_clé}'
if client and client.channel:
video = VideosSearch
musics[ctx.guild].append(video)
else:
ytdl_options = {
'noplaylist': True,
'default_search': 'auto'
}
ytdl = youtube_dl.YoutubeDL(ytdl_options)
video = ytdl.extract_info(link, download = False)
if 'entries' in video:
video_format = video['entries'][0]["formats"][0]
elif 'formats' in video:
video_format = video["formats"][0]
url = video["webpage_url"]
stream_url = video_format["url"]
channel = ctx.author.voice.channel
musics[ctx.guild] = []
client = await channel.connect()
await ctx.reply(f"Je suis là pour vous ambiancer")
play_song(client, musics[ctx.guild], stream_url)```
Traceback (most recent call last):
File "C:\Users\THEO\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\THEO\cinébot\main.py", line 59, in on_command_error
raise error
File "C:\Users\THEO\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\THEO\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\THEO\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'stream_url'
Have you tried to subclass Bot in that game class?
wdym?
You can subclass the Bot class of discord.py or whatever package you are using
ye discord.py
https://github.com/Tvrsier/BaseBot here is an example how to do it
Base bot setup for discord.py and relative forks. Contribute to Tvrsier/BaseBot development by creating an account on GitHub.
can i get someones timezone with bot
please
is that going to help with the specific thing im trying to do tho?
It will come in handly, since you declare the bot in your game class with this one your game class will also be an instance of Bot
rn im focused more on fixing what i got than implementing new features
im not following why that is useful rn
The error is not there
Because you will have more control over the bot while the game runs
Traceback (most recent call last):
File "C:\Users\THEO\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\THEO\cinébot\main.py", line 59, in on_command_error
raise error
File "C:\Users\THEO\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\THEO\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\THEO\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'stream_url'
yeah the error is saying that you are trying to use stream_url as an attribute of string object
so you will have something like var.stream_url somewhere
So how to correct this ?
they are two fields with /n inside the value
You have the line where the error is raising
no
@placid skiff https://github.com/Ash-02014/_ 😔 check this out asap
File "c:\Users\THEO\cinébot\main.py", line 59, in on_command_error
raise error

What should I change then ?
yeah
that line 
||Ash please take me out of here||
asking for help from the diavolo? 😔
so I remove raise error ?
I still need to fix a couple of things in the code
I would sell my soul if they learned python before starting with d.py
copy the line 59 in your main.py file here
that's my repo lamo
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send("You're on cooldown, retry in 30's")
return
else:
raise error```
I didn't even read any of the convo, I was making the nice underscore-based bot, and yes, that was my repo 

wht can i do if the hybrid commands doesn't get registered ?
Now you will have to make a program which converts every of those thing into human language
How to make a button which can only be clicked by a user with a particular role?
no.
That's a bot, and it surely can be read by an human upon strain
you'll have to check if the user has a role once they click it, use the interaction_check function for that purpose
Outside the class?
lets say you have a generator of integers, how do you make it a list and remove all the 7's from it in one line
Can someone help me with this?
class UwUButtonViewClass(discord.ui.View):
async def interaction_check(interaction: discord.Interaction) -> bool:
return (role in interaction.author.roles)
lets say you have a generator of integers, how do you make it a list and remove all the 7's from it in one line
Can someone help me with this?
could you not spam?
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.
Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
please abide to rule 7 (#rules)
should i install any lib to use slash cmnd in dpy 2.0 ?
Nope
uhh
import datetime as dt
import json
import random
from datetime import datetime
import discord
import requests
from discord import app_commands
from discord.ext import commands
class hyb(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@commands.hybrid_command(name="pingo")
async def ping_command(self, ctx: commands.Context) -> None:
await ctx.send("Hello!")
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(hyb(bot),guilds = [discord.Object(id = 845317571301081158)])
print('hyb')
is this correct ?
Can I use
if role in interaction.author.roles:
. . .
Inside this Check
sure
discord.Embed(title="Some title for the embed", description="description for the embed", colour/color=hexcode/rgb/discord.Colour/discord.Color, url="url to make the embed title a hyperlink") #NOTE: All the arguments in the __init__ constructor of Embed class are optional
embed.add_field(name="name for the field", value="some value", inline=False) #NOTE: Every argument except "inline" is required
but make sure that it always return True or False
👀
Sparky
Uhm
..
interesting
?
...?

huh?
Guys, I wanna make a bot for counting. At least it should delete all messages which contains any letters and symbols in it, only numbers are available!
Second, if someone know, how to make participants send numbers only in order, for example: 1 2 3 4, but if after that someone sends 55, the bot should sting him - because there should not be 55 but 5!
Please help me 🙂
create a list of command groups with the embed already in them and when someone click the button you show that embed, without removing the rest of the buttons
how can i make command that when triggered it will send a message/embed with reaction and when you click the reaction it will do something?
idk how to make the check
How to check channel permissions?
I need to check if everyone role sees a channel. If message read == True for everyone role ....
!d discord.on_raw_reaction_add
discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
i know this one but i don't want a event, i want it to be in command
does it work still the same?
@client.command()
async def edonate(ctx, event, prize, *, msg):
embed1 = discord.Embed(title=f"{ctx.author.name} wants to make an event donation!", description=f" \n:dot_877959363388641300:**Event:** {event} \n:dot_877959363388641300:**Prize:** {prize} \n:dot_877959363388641300:**Message:** {msg}", color = discord.Colour.random())
embed1.set_author(name=ctx.guild.name)
await ctx.send(embed=embed1, view=Buttons1())
``` embed sent twice
The event is called whenever a reaction is addedd so it will work for the command too, otherwise you can use wait_for to check for a single event
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
kk
I suggested holding a 'Python Object Oriented Programming Seminar', but the acronym was unpopular.
!d discord.TextChannel.permission_for
No documentation found for the requested symbol.
I had a problem so I thought I'd use Java. Now I have a ProblemFactory.
lmao
!d discord.TextChannel.permissions_for
permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role").
This function takes into consideration the following cases...
Where are those money stored?
you need to edit that json of that member then
Well if you don't do it the money will remain as they are stored
whatever changes you do you will have to change it into the json too
you will have to write it 
things will not be done with magic 
there is no "builtin" relations between a member object and the data stored in your json
so every changes to the member object must be done in the json too
that will change the value for your code only
in that code you edit your json in your last two lines
Non-UTF-8 code starting with '\x95' in file t.py on line 49, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
Anu wgo know how to fix
Python Enhancement Proposals (PEPs)
can u show code
uh
what the-
why would you do that, just why
....Hunter?
nice
property guild_permissions```
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.
Changed in version 2.0: Member timeouts are taken into consideration.
Nice
the error pretty much says it all
how make dizcord bot
no.
ok
at least tell them what tutorial 
U r tryna add all the permissions in one single value
Hunter's smort
how to get the highest role the bot can access and the role that are lower than the highest role
ctx.me.roles
i dont mean bot
i was making a lock command basically
the role that falls on the superior hierarchy, right?
Get the last role (iirc) in the list that's the highest role bot has
no
!d discord.Member.top_role
property top_role```
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
I forgot that existed
wdym by superior hiearchy
the highest role that bot can edit
and the roles lower than that
Thats not how a lockdown command works tho @slate swan
Mb
you gotta change the channel's permissions
channel.overwrites_for(ctx.guild.default_role)
U edit the permissions for everyone role
isnt this everyone role @maiden fable
that doesnt work ..
some ppl can still send msg!
ok so
@slate swan stop
what
dont delete messages!
okay!
Yes
.
it does lock but ppl having different role can send msg
😐
Sad
no sad help me!
channel = channel or ctx.channel
overwrite = channel.overwrites_for(ctx.guild.default_role)
if overwrite.send_messages == True:
try:
embed = disnake.Embed(description=f"Locked {channel}",color=green,timestamp=datetime.utcnow())
await channel.set_permissions(ctx.guild.default_role, send_messages=False)
await channel.send(embed=embed)
except:
embed = disnake.Embed(description=f"Cannot lock {ctx.channel}",color=red,timestamp=datetime.utcnow())
await ctx.reply(embed=embed)
else:
embed = disnake.Embed(description=f"{channel} | Is Already locked",color=red,timestamp=datetime.utcnow())
await ctx.reply(embed=embed)
Does it send the embed in the except block?
it sends the else statement ;-;
its old dirty code i havent touched it since months
Ok
i guess i added it when i was learning
Ig the problem is the send_messages may also be None
um let me check
You should kinda revert your if construction
Check if overwrite.send_messages is False and execute the code you had in else statement
ur right it return None ;/
i tried printing
Means the permission is not set and basically it is true
alr let me reverse
how can i deleted channel using his name
@vale wing worked 💀
In a command?
Gg
i also got locked 💀
Lmao
You can just typehint channel argument with TextChannel, it will automatically find the channel with that name if it exists
thanks for the help :D
Np
ok
@bot.command()
async def delete(ctx, channel: discord.TextChannel):
await channel.delete(reason=f"Deleted by {ctx.author}")```
Something like this
Don't forget to add checks so common users can't use this command
i don't want that like this sorry i'll explain
i have bot that creates a channel for party with that person he selected so the name is {ctx.author.name} {member.name} and i want command that when you type something like this -partyend {member: discord.Member} it will delete the channel
is that possible?
cant understand
the channel name?
ok i understand now
i have command -connect member that will create private channel for you and the member. the name of the channel is your name his name
What's the point in hiding the footer?
its wrong time
and when you type -partyend member it will delete the channel
ok so create the channel with the party member's name
yes
and i know you can delete channel using his id or name but i forgot how to do it
You mean.. discord.abc.GuildChannel.delete/discord.TextChannel.delete
yeah ```py
from discord.utils import get
specific_name = 'sam582s-lounge'
channel = get(guild.channels, name=specific_name)
await channel.delete()
i'll try
async def party(ctx,member : discord.Member):
await ctx.guild.create_text_channel(name=member.name)
async def partyend(ctx,member : discord.Member):
a = discord.utils.get(ctx.guild.channels,member.name)
await a.delete()
@stable leaf
?
i used this
i'll go test it
..
👍
how would i delete a voice channel?
voice = get(ctx.guild.voice_channels, name=f"{ctx.author.name} {membed.name}")
like that?
voice.delete()
ye
but is it ctx.guild.voice_channels?
ctx.guild.voice_channels , yes
thx
Guys, I wanna make a bot for counting. At least it should delete all messages which contains any letters and symbols in it, only numbers are available!
Second, if someone know, how to make participants send numbers only in order, for example: 1 2 3 4, but if after that someone sends 55, the bot should sting him - because there should not be 55 but 5!
Please help me 🙂
Just do to everyone permission view the channel, but disable connect permission to voice channel . Really no need bot for this
Why did you asking then
Oh ok
Anyone? Please help me 
Yeah ok sure
Voice of course
It is discord bots channel...
Ehh, no one can help.. Plz help...
Right bro
It is only for you
For all members it is locked
It is only for admins
Not any way, for all members it looks like you wants for admins and owner no
Because admins can do anything, and connect to anything
Try to view server as member
hello
Nah it is not
Yes, you just did it
If someone have admin permission or permission to connect, they can join it
Not any way
I didn’t understand you.. You cannot lick channel from yourself
YOU JUST DID IT, VIEW your server as “member” role
And you will aee, this channel is locked
Check in YouTube.. it is working.
I know, but he not
The last time, anyone ?)
Please...
Yeah
does anyone know why my bot.user.id is giving none for the first 2 seconds on boot
Guys, I wanna make a bot for counting. At least it should delete all messages which contains any letters and symbols in it, only numbers are available!
Second, if someone know, how to make participants send numbers only in order, for example: 1 2 3 4, but if after that someone sends 55, the bot should sting him - because there should not be 55 but 5!
Anyone can help, I just wanna counting bot😦
bot command
Ping me if you know
@bot.command()
async def pay(ctx, amount, discord.Member = None)
....
Yeah it is bot command. You should have prefix ~ first of all. If you have,
This is right
can someone help
Oh ok
No sorry... This... 😕
just change bot.command() to client.command() @slate swan
i assumed u defined it as bot since bot > client

well lemme see ur code
so i can see how ur currency works
!code