#discord-bots
1 messages · Page 795 of 1
for example ?command @amber beacon#1234
the bot should know its trying to find user#1234
so from mention, i would say
Ok
@command()
async def command(ctx, member: discord.Member):
thanks
unless you do something weird like get_member(int(member.strip('<@!>'))) inside the function
🗿
and if i want the command to give out a specific role to this user? i tried ctx.member.add_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.
And does that not work?
yeah
Thanks! Really do appreciate it :)
async def verify(ctx, member = discord.Member):
vrole = discord.utils.get(ctx.guild.roles, id=815652214198370334)
await ctx.member.add_roles(vrole))```
honestly i wouldnt be surprised if everything in this is wrong
i removed that lol
It’s member: discord.Member
forgot to do it while copy pasting
Is it true that after a certain amount of time discord.py will be unusable?
i mean yeah it lost support
well it still doesnt work
I don’t think you need the ctx before member.add_roles
works now
NOTE: global commands can take up to 1 hour to show up after registration.
what does this means
i have to wait a hr to see changes in app??
wtf is a global command? Slash commands usually take time to show up though
Yeah I’m aware it’s usable, but wouldn’t it unusable after some time?
so maybe that’s what it means
no it shouldn’t be
well it is still a lib and there is no point to not make it work anymore
Well once discord start releasing new breaking things I’m pretty sure users who want to have a verified bot won’t be able to use
well yeah it doesn’t have slash commands or things like that
so that’s why it’s recommended to use a fork
Mhm
Global cmds basically means, Slash cmds which will be available to use through all the guilds your bot is in
how do i make the bot delete the last 2 messages in a channel
So... this takes one hour to update in app?
If u want the cmds to be added instantly for testing, use the guild_ids param in ur fork
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
Yes global take an hr and specific guild@ones happen instantly
so i have to provide my guild id to update instantly?
As a matter of fact lol one of the helpers for permission to make a lib called Slash_util which brings application cmds to ur bot, this was done majorly so users don’t use forks etc lmao
Yes
If ur testing then sure
Those 3rd party libs prolly won’t be as good as the forks will be tbh
But it will be available only that specific guild
but also watch the non-forks like Pincer and Hikari
is it possible to get the bot the search a user id, as ex. i have a string "gorgonzola" can it search for my id? ofc if im on the server
!d discord.Message.author
if your the message author you just need to use that
doesn't seem to work
what i (someone thats horrible at this stuff) tried
await discord.Message.delete(2)
no, if im not the author how do i do that
I don’t think a string can search for a user my man
a example would be !rank gorgonzola, could it search for my id and get my rank in the db
oh
It’s for deleting a specific/ provided message
oh
If u wanna go achieve what u want do
you could do something like this @haughty quartz
SyncWarning: Failed to overwrite commands in <Guild id=937778685866565732> due to 403 Forbidden (error code: 50001): Missing Access```
async def rank(ctx, member: discord.Member = None)
it makes the second parameter after !rank be the member you want to get
The error states the issue
i see
Ur bot doesn’t have the slash cmd scope (application.commands) ig
Kick and invite it with that scope
So the command invocation would be !rank <@member>
and then i could just use member in my code
yes but can it get the member without pinging and without using a id
oh wait I see what you mean
!rank gorgonzola and not !rank <@gorgonzola>
!d TextChannel.purge this should work
I guess you could setup a converter that changes the string to find that users name if that is possible
That just came off the top of my head but idk if that’s possible
i mean something like that is possible as bigger bots use it afaik
do i need to specify what channel i want it to be somehow?
If u type hinted the member param then dpy will convert it so u should be able to either use their name, ID, mention
It should work
what exactly do you mean? can you give a example?
So I have a really weird issue with one of my commands where it's not responding and isn't giving me any errors. I do have a error handler and some members of the dpy server told me I should check out the error handler tag bc my error handler was eating my error (I don't think it is bc it error's correctly for every single other command, and all of those commands work). here is my error handler: https://sourceb.in/fL9sEcdmAl
My command that's not working:py @commands.has_permissions(administrator = True) @commands.guild_only() @commands.command(description = "Sets the bad words that aren't allowed to be said on the server.") async def bad(self, ctx, *, words: str): print(f"Input: {words}") data = await self.bot.get_data(ctx.guild.id) bad_words = [] #bad_words.append(data[28]) for word in words: bad_words.append(word) print(f"Bad Words: {bad_words}") async with self.bot.pool.acquire() as conn: await conn.execute("UPDATE data SET badwords=$1 WHERE guild=$2", [word for word in bad_words], ctx.guild.id,) await ctx.send(embed = discord.Embed(description = f"The bad words list has been update to be `{', '.join(data[28])}`.", colour = self.bot.primary_colour))and my get_data function:py async def get_data(self, guild): async with self.pool.acquire() as conn: res = await conn.fetchrow("SELECT * FROM data WHERE guild=$1", guild) if not res: res = await conn.fetchrow( "INSERT INTO data VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29) RETURNING *", guild, None, None, [], None, None, None, False, [], [], False, [], [], 0, False, 7, None, [], None, None, 0, 0, None, None, None, None, 0, None, [], ) # guild, prefix, category, access roles, logging, welcome, goodbye, logging plus, ping roles, blacklist, anonymous, locked roles, raid channel, current count, raidmode status, acc_age, raidmode log, mistakes role, join/leave log, raidrole, isolation time, guild mistakes, counting channel, deleted messages log, edited messages log, suggestion channel, suggestion count, starbaord channel, bad words return resand what's really weird is that even if I comment out every single bit of code minus the very first print statement it still doesn't do anything which makes me think the commands not being registered or something even tho it appears in my help menu
Holy shit
and how? do i need to add a parameter?
the doc doesn't explain it well
im my eyes, at least
async def rank(ctx, member: discord.Member = hinted)
``` ?
Sure, so I have a cmd let’s take:
async def test(ctx, member: discord.Member):
await ctx.send(f”You chose {member.name}”)
So if I run this code these are the possibilities:
!test @prime ibex
!test 278282828282
!test ASF
All of these will return: You chose ASF
in the third case, the member argument needs to be all Capitals
👀 thanks :)
asf won't get a member named ASF
u already type hinted It by doing member: discord.Member
@flat solsticefirst thing i can spot is u nvr commit the exeute of update
Welcome
Welcome
discord.Member searches it?
Yes
awesome
Yeah lol it’s an example, I’m on Phone so u know
Thanks for pointing out, kinda tough to do so much on mobile xD
again, how? i tried reading the documentation.
Thanks for the tip, doesn't help me identify the root cause of the command not responding but I always appreciate advice on how to make better SQL statements
is not necessary with asyncpg
it's not executing the first print?
how do i purge above 10 messages?
above 10 messages as in more than 10 messages?
yes
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Examples
Deleting bot’s messages...
oh pregrep i nvr used that explains why i thought $1 was weird
@flat solsticeis the update not working or is the fetch not working?
Here use this example:
async def clear(ctx, amnt: int, channel: discord.TextChannel):
await channel.purge(limit = amnt + 1 )
Nice
@prime ibex how do i get the member's name when having a id
fetch it
?d discord.Member
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s name with the discriminator.
u need a user/member object
It has a name attr
okay
Here in this example I showed it
theres few names tho, uhave username (name) and serverside nick aka display_name
yeah that works fine
Cool
yeah right, kind people here
yup
correct
Mhm
do you have anything else called bad in the cog class
none of the commands working, including the first print statemt, which it was makes me think somethings very broken
Do you have an on_message?
If the first print statement isn’t getting called then somethings wrong yes
nope, just double checked and this command is the only time bad is mentioned in this cog and altho it is mentioned in other cogs those are all bad arguments as part of the error handler
are there any other commands in the cog, and are they working?
yep, in a separate cog, and it's not sending errors either.
also to clarify when i said
none of the commands working
I ment none of the code in thisbadcommand are working, all of my other commands are working fine
Can we see the on_message?
It’s usually the culprit of commands that aren’t working
And is the on message an event or a listener?
yes there are other commands in the cog and yes they are working correctly and some of them reference the same table (albeit different columns)
Interesting. Could you share the cog please?
also if you have jishaku, try printing [c.name for c in _bot.get_cog(...).get_commands()] and see if you can find bad there
@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot:
return
if message.guild != None:
data = await self.bot.get_data(message.guild.id)
server_info = self.bot.get_channel(id = 500413330368888882) # Server Info channel
text = f"Please don't mention `@everyone` unnecessarily. If you want to ping a large group of members we have roles for activities or games which can be found in {server_info.mention} or you could ping `@here`."
if bad := [word for word in data[28] or self.bot.config.default_bad_words if word in message.content]:
#if message.content in data[28] or message.content in self.bot.config.default_bad_words:
#if message.author.has_any_role(data[3]) or message.author.has_guild_permissions(self.bot.config.moderator_permissions):
if (len(set(data[3]) & set([role.id for role in message.author.roles])) > 0) or self.bot.config.moderator_permissions in message.author.guild_permissions:
return
else:
await message.delete()
if "@everyone" in message.content:
try:
await message.author.send(text)
except discord.HTTPException:
await message.channel.send(f'{message.author.mention} {text}')
try:
await message.author.send(f'Your message had `{", ".join(bad)}` in it, This word is conssidered a "bad" word on this server so your message was removed.')
except discord.HTTPException:
await message.channel.send(f'{message.author.mention} `{bad}` is conssidered a "bad" word on this server.')```this isn't the full event as it's much too long so I'll put it online and send the link however I don't think this event will be causing the issues (hopefully) bc it's never been the culprit of the bot not working https://sourceb.in/ecwK4dMizG
async def purge(ctx, a=100):
await ctx.channel.purge(limit=a + 1)```
if someone doesn't specify how many messages to purge, how do i make it give an error?
make it required because now it’s optional
or
if a is None
I believe that should work
If you make it required d.py will automatically raise a MissingRequiredArgument error iirc
^
You can then catch that error somewhere
here's a link, it's chunky and has rather a lot of redunant code which I need to trim at some point but find useful to reference atm https://sourceb.in/8ANxNed6ta
i tried that, doesn't work
Problem is not with the on message
Is the cog being registered properly?
then make the parameter required
by removing =100
If you have jishaku you can print all the cogs
If not just do it on startup or a test command
@flat solstice while im going through the code, could you try this ^
yep, all the other commands in the cog work without issue. and i'm using dpy and have never heard of jishaku so i'm thinking it's some fork or something
that just breaks the command
no
https://jishaku.readthedocs.io/en/latest/ it's a debugging extension
That’s quite a strange error
Or behavior to be more specific
okay well i don't have that, guess I'll get that; should I be getting the as API or as Cog part
Try removing all the decorators except the barebones @commands.command() without any arguments
as Cog
@client.command()
async def purge(ctx, a:int = None):
if a is None:
return await ctx.send(“Please provide an amnt”)
await ctx.channel.purge(limit=a + 1)
Do something like that
^ @silver magnet
^^^
ohh the return
very fancy return await
Mhm if u don’t return then it will execute the other part of the code as well
xD
Btw is this a bad practice :-
//Return Something
//Do something else```
Like I didn't use else statment
Because it's already returning in if
Hmm
Personally I prefer to do what you did there
Same
ye
hello
wuts going on here
Discord bot talk
hm
?
damm
lol
u want guild icon for wut lol
that legit the fucking thing
!d discord.Guild.icon
property icon: Optional[discord.asset.Asset]```
Returns the guild’s icon asset, if available.
is there a way i can find what activity a user is doing
as in game activity or status (do not disturb, etc)
!d discord.Member.activity
property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.
Note
Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.
Note
A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
hm
Is it possible to make your bot screenshare?
What about a discord account?
wut
like i can have an alt act as a bot and screenshare
!pip selenium
umm
i dont think its possible
okay setting this up is taking a while
!pip keyboard
!d keyboard
Unable to convert 'typing' to valid command, tag, or Cog.
had to set up the cog, didn't I?```py
from discord.ext import commands
from jishaku.cog import STANDARD_FEATURES, OPTIONAL_FEATURES
from jishaku.features.baseclass import Feature
log = logging.getLogger(name)
class CustomDebugCog(*OPTIONAL_FEATURES, *STANDARD_FEATURES):
@Feature.Command(parent="jsk", name="foobar")
async def jsk_foobar(self, ctx: commands.Context):
await ctx.send("{[c.name for c in _bot.get_cog(...).get_commands()]}")
def setup(bot: commands.Bot):
bot.add_cog(CustomDebugCog(bot=bot))```
not at all
oh
xd
essentially you just load the extension and then use the jsk py command to evaluate code
and I add the extension from inside my problem cog
you can add it anywhere, wont matter
you just need jsk to quickly evaluate code from a running bot
Oof just add that bot.load_extension() part which Zeffo send earlier after ofc downloading the module , after where u created ur bot object ie bot = commands.Bot(…)
guys
Just below that add that part and ur good to go
halp
example
okay i it's loaded, tried the command and got told I don't have permissions to use the command
does discord have an event when a user starts an activity
are you not the bot owner?
yes, but not the server owner of that guild
wait which command are you talking about
jishaku only requires you to be the bot owner
,jishaku [c.name for c in _bot.get_cog(...).get_commands()]
try ,jsk py
,jsk py [c.name for c in _bot.get_cog(...).get_commands()] and same error
are you sure you're the bot owner 👀
lmaooo
😼
yep
it's raising commands.NotOwner?
Try adding the owner_id = ur id kwarg in your bot constructor
well I have a owner and owners param in my bot, my ID is in both sections
Could u send a snippet of ur bot constructor?
What error is it raising
# The main bot owner
owner = 446290930723717120
# Bot owners that have access to owner commands
owners = [
446290930723717120,
381998065327931392,
365262543872327681,
]```and ```py
bot = GoPostal(
intents=discord.Intents(
guilds = True,
members = True,
presences = True,
messages = True,
reactions = True,
),
member_cache_flags = None,
chunk_guilds_at_startup = config.fetch_all_members,
command_prefix = _get_guild_prefix,
case_insensitive = False,
help_command = None,
owner_id = config.owner,
heartbeat_timeout = 300,
shard_ids = shard_ids,
shard_count = shard_count,
cluster_id = cluster_id,
cluster_count = cluster_count,
version = "2.1.1",
),```
ah jsk will only take into account bot.owner_id
you'll want to set this
instead of owner_id
Seeing from the owner_id kwarg that’s the issue
Ur id is 365262543872327681
can i still have both, even if it jsk only takes owners_id or would having both break it
Whereas the bot is using the id starting from 4
it would break, dpy doesnt allow setting both
iirc no
I don’t see what’s the issue?
owner_ids should be more than enough
oh it is
Replace the owner_id with owner_ids and set its value to config.owners
okay made that change and it broke the bot, now it's telling me that the help command already exists when it tries to register it
you prolly removed the help_command = None, by accident
Hello my welcome message is still acting up with no errors in the console doesn't work py @commands.Cog.listener() async def on_member_join(self, member: discord.member): if member.guild.id == 902404450432483378 : return channels = member.guild.channels for channel in channels: if ('welcome' in channel.name.lower()) or ('joins' in channel.name.lower()): #or ('testing' in channel.name) await channel.send(f"A new soldier named, {member.mention} , has joined **Bro's SMP War!** Make sure to check out [#806264072454537267](/guild/267624335836053506/channel/806264072454537267/) and [#899440312223662121](/guild/267624335836053506/channel/899440312223662121/) first before doing anything else.") but this does work ```py
@commands.Cog.listener()
async def on_member_remove(self, member: discord.member):
if member.guild.id == 902404450432483378 : return
channels = member.guild.channels
for channel in channels:
if ('leave' in channel.name.lower()) or ('goodbye' in channel.name.lower()) or ('graveyard' in channel.name.lower()):
if isinstance(channel, discord.TextChannel):
await channel.send(f"{member} left the server because they suck :+1:")
it was working fine then all of the sudden it doesn't
at all
nope that was still there, I'd just loaded the wrong main file 
Shorter
i've done that a few times
okay, so i did that command ,jsk py [c.name for c in _bot.get_cog(...).get_commands()] and the bot dmed me this nice traceback py Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/jishaku/features/python.py", line 145, in jsk_python async for send, result in AsyncSender(executor): File "/usr/local/lib/python3.8/dist-packages/jishaku/functools.py", line 109, in _internal value = await base.asend(self.send_value) File "/usr/local/lib/python3.8/dist-packages/jishaku/repl/compilation.py", line 140, in traverse async for send, result in AsyncSender(func(*self.args)): File "/usr/local/lib/python3.8/dist-packages/jishaku/functools.py", line 109, in _internal value = await base.asend(self.send_value) File "<repl>", line 1, in _repl_coroutine [c.name for c in _bot.get_cog(...).get_commands()] AttributeError: 'NoneType' object has no attribute 'get_commands'
oh replace ... with the cog name
Maybe the guild channels aren’t satisfying those if conditions
but the conditions are met and i use the same format for the leave
Because in the next code bloc of member leave, ur also checking whether it’s an valid channel or not, whereas in the member join u aren’t
There a few reasons to it
- You don’t have member intents enabled in ur code or developer portal
- that if condition is failing
- your error handler is eating the error (mostly)
i don't got an error handler for that
It might be possible the the condition is failing
and i belive i have it turned on in the dev portal i never turned it off though
,jsk py [c.name for c in _bot.get_cog(Moderation).get_commands()] returned py Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/jishaku/features/python.py", line 145, in jsk_python async for send, result in AsyncSender(executor): File "/usr/local/lib/python3.8/dist-packages/jishaku/functools.py", line 109, in _internal value = await base.asend(self.send_value) File "/usr/local/lib/python3.8/dist-packages/jishaku/repl/compilation.py", line 140, in traverse async for send, result in AsyncSender(func(*self.args)): File "/usr/local/lib/python3.8/dist-packages/jishaku/functools.py", line 109, in _internal value = await base.asend(self.send_value) File "<repl>", line 1, in _repl_coroutine [c.name for c in _bot.get_cog(Moderation).get_commands()] NameError: name 'Moderation' is not definedik the names correct since I copied it from the cog itself and the cog is appearing in my help command `altho that;s provided by a third party lib called slashhelp so maybe it's fetching it in a different way)
make it a string
[c.name for c in _bot.get_cog("Moderation").get_commands()]
me so dumb
U sure u don’t have any global error handler??? In any other cog
okay that returned py ['raidmode', 'lockdown', 'unlockdown', 'lockchannel', 'unlockchannel', 'lockpreset', 'unlockpreset', 'age', 'bad', 'raidrole', 'clear', 'massban', 'modconfig', 'viewconfig']
Is there some video on disnake? tutorials
I have a purge error handler not a global
Interesting, so the command is being registered
How were you invoking bad?
,bad act2 b2b
Ok so in ur code members intents is enabled right ?
You're an admin in the guild you're testing in?
hmmmm yep
Cool so now we know for sure it’s the condition failing
yep
ok so how do i fix the condition so it is not failing?
Ok, let's try invoking the command with jsk: ```py
await _ctx.invoke(_bot.get_command('bad'), "act2", "b2b")
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/jishaku/features/python.py", line 145, in jsk_python
async for send, result in AsyncSender(executor):
File "/usr/local/lib/python3.8/dist-packages/jishaku/functools.py", line 109, in _internal
value = await base.asend(self.send_value)
File "/usr/local/lib/python3.8/dist-packages/jishaku/repl/compilation.py", line 140, in traverse
async for send, result in AsyncSender(func(*self.args)):
File "/usr/local/lib/python3.8/dist-packages/jishaku/functools.py", line 109, in _internal
value = await base.asend(self.send_value)
File "<repl>", line 1, in _repl_coroutine
await _ctx.invoke(_bot.get_command('bad'), "act2", "b2b")
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/context.py", line 144, in invoke
ret = await command.callback(*arguments, **kwargs)
TypeError: bad() takes 2 positional arguments but 4 were given```
how would i redo it?
await _ctx.invoke(_bot.get_command('bad'), words="act2 b2b")
okay now it's getting tripped up on the db, which I understand it probs can't accesspy Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/jishaku/features/python.py", line 145, in jsk_python async for send, result in AsyncSender(executor): File "/usr/local/lib/python3.8/dist-packages/jishaku/functools.py", line 109, in _internal value = await base.asend(self.send_value) File "/usr/local/lib/python3.8/dist-packages/jishaku/repl/compilation.py", line 140, in traverse async for send, result in AsyncSender(func(*self.args)): File "/usr/local/lib/python3.8/dist-packages/jishaku/functools.py", line 109, in _internal value = await base.asend(self.send_value) File "<repl>", line 1, in _repl_coroutine await _ctx.invoke(_bot.get_command('bad'), words="act2 b2b") File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/context.py", line 144, in invoke ret = await command.callback(*arguments, **kwargs) File "/home/modmail/cogs/moderation.py", line 157, in bad await conn.execute("UPDATE data SET badwords=$1 WHERE guild=$2", [word for word in bad_words], ctx.guild.id,) AttributeError: 'NoneType' object has no attribute 'id'
@prime ibex ??
yep, bc it doesn't seem to be doing anything in a server
Does the bot have read message permissions in that server?
It should work just fine in a server
how can I get a member object using ID?
Guild.get_member
yep it has admin, and it had been responding to the command before and sending me tracebacks but as soon as i try to execute a invocation it stopped responding
So jsk works as long as you aren't invoking a command?
yep
Do you still have that print in the command?
okay just tried ,jsk print("hello") and got nothing, does it respond to prints
How to tell what wait_for was completed?
I just have a task complete object
async def test(self, ctx):
react = '👋'
msg = await ctx.send('React or say hi for a response')
await msg.add_reaction(react)
done, pending = await asyncio.wait([
self.bot.wait_for(
'reaction_add',
timeout = 25.0,
check = lambda reaction, user:
user == ctx.author
and reaction.message == msg
and str(reaction.emoji) == react
),
self.bot.wait_for(
'message',
timeout = 30.0,
check = lambda message:
message.author == ctx.author
and message.content == "hi"
)
],
return_when = asyncio.FIRST_COMPLETED
)
for future in pending:
future.cancel()
await ctx.send('Done')
print(done.pop().result())
Im pretty sure you need the py subcommand
trying to wait for 2 events
it works, but I can't tell which event was triggered
@maiden fable any idea?
Just do ,jsk py 1
It should send 1
how would i make a new welcome message because my last one failed
I tried to use it to add roles to a user but guild.get_member returns None
what have you tried?
#discord-bots message just scroll i have a whole convoerstion on what it is
okay well i got it to send hello print but it's not doing ,jsk py await _ctx.invoke(_bot.get_command('bad'), words="act2 b2b")I gtg eat for a bit now so I'll msg when I get back
oh I'm an idiot I forgot to add intents 🤦♂️
first of all, you can use guild.text_channels, you don't have to loop through other channels
second of all, I want to know what you tried and what didn't do what it should when you tested
Oh I had gone AFK, hmm so try getting the channel using discord.utils.get(member.guild.channels, name = “channel_name ur looking for”)
it works fine then it just stopped working but it should go like this witch it did then just stopped working and i didn't touch it
check first of all if you're not overwriting the event AND if it even gets invoked when someone joins
bruh i use both dark and light
because i can change my screen brightness by a single button
Well that will work only if they are providing a fixed channel ID, based on their use case they are trying to get the channels with specific names in that server
that would work because i just need a channel for now that is from my multiple guild server not my 2 guild bot where i don't even use the other welcome message in the other guild
channel = discord.utils.(member.guild.channels, name = “welcome or whatever name it is”
if channel:
await channel.send(“…”)
text_channels and in pls
Why do u wanna do all that lol when discord.utils is doing that for u?
^^^ making ur code more easy to understand
Nah it isn’t else it wouldn be there
Even r Danny rewrite has it in some places
lmfao this channel is more active than #python-discussion
is dpy the most cloned project ever? 
certainly not
so like this then? ```py
@commands.Cog.listener()
async def on_member_join(self, member: discord.member):
if member.guild.id == 902404450432483378 : return
role1 = member.guild.get_role(933104091066941530)
role2 = member.guild.get_role(936481481113632839)
role3 = member.guild.get_role(936712347211419708)
role4 = member.guild.get_role(936712664950931476)
role5 = member.guild.get_role(842254098266718219)
role6 = member.guild.get_role(842253873376264222)
role7 = member.guild.get_role(842254463309316136)
role8 = member.guild.get_role(842260259417489448)
role9 = member.guild.get_role(842260429044842572)
role10 = member.guild.get_role(893308041699680337)
role11 = member.guild.get_role(816838497159610369)
role12 = member.guild.get_role(826636738306506794)
role13 = member.guild.get_role(841144860966125568)
role14 = member.guild.get_role(893308556596641792)
roles = [role1, role2, role3, role4, role5, role6, role7, role8, role9, role10, role11, role12, role13, role14]
await member.add_roles(*roles)
channel = discord.utils.member.guild.channels, name = "welcome"
await channel.send(f"A new soldier named, {member.mention} , has joined Bro's SMP War! Make sure to check out #806264072454537267 and #899440312223662121 first before doing anything else.")
bruh
Possible to create a webhook for a channel with discord.py?
for loops
confused
learn how to use utils via the docs too
also, the implementation only looks for a MATCH with welcome, not if welcome is in its name, but I'll just stop helping since you didn't read my previous messages
ok i will
Omg that’s so inefficient to get so many roles, anyways change the utils part to: discord.utils.get(member.guild.channels, name = “welcome”)
then before sending do:
if channel:
await channel.send(“…”)
Alrighty
read my previous message too, your implementation isn't what he wants
no
multiple guilds
Oh I thought he was using for a mutli server bot, where he’s trying to get a channel named called welcome
Damm how can you even think about using light mode
It will probably kill your eyes
it just needs "welcome" in its name
very true
It seems he’s really confused as to what he’s trying o properly achieve
I want to role members with 14 different roles on join and want to send a welcome message
no, ofc not
nope just one
the ID will only match in one guild
bingo
right?
isn't self for the cogs witch i am working in?
and self has to be everywhere lol
cool i just need it for one anyway
hello i have this code and am trying out slash commands but its not working. im not getting any errors but its not showing the commands. any ideas why?
please ping me when you answer my question
I'm just saying that get_channel is useless if you're using multiple guilds, since it'll only match with one of those
the self.guild is irrelevant
not in this bot i have 2 with the same commands just different functions and i know the channel id 880619564935811132
ok so it looks like this then and how do i make the roles list smaller in size? ```py
@commands.Cog.listener()
async def on_member_join(self, member: discord.member):
if member.guild.id == 902404450432483378 : return
role1 = member.guild.get_role(933104091066941530)
role2 = member.guild.get_role(936481481113632839)
role3 = member.guild.get_role(936712347211419708)
role4 = member.guild.get_role(936712664950931476)
role5 = member.guild.get_role(842254098266718219)
role6 = member.guild.get_role(842253873376264222)
role7 = member.guild.get_role(842254463309316136)
role8 = member.guild.get_role(842260259417489448)
role9 = member.guild.get_role(842260429044842572)
role10 = member.guild.get_role(893308041699680337)
role11 = member.guild.get_role(816838497159610369)
role12 = member.guild.get_role(826636738306506794)
role13 = member.guild.get_role(841144860966125568)
role14 = member.guild.get_role(893308556596641792)
roles = [role1, role2, role3, role4, role5, role6, role7, role8, role9, role10, role11, role12, role13, role14]
await member.add_roles(*roles)
channel = self.guild.get_channel(880619564935811132)
await channel.send(f"A new soldier named, {member.mention} , has joined Bro's SMP War! Make sure to check out #806264072454537267 and #899440312223662121 first before doing anything else.")
No documentation found for the requested symbol.
get_role(role_id, /)```
Returns a role with the given ID.
property roles: List[discord.role.Role]```
Returns a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of the guild’s roles in hierarchy order.
The first element of this list will be the lowest role in the hierarchy.
Lol terminal freezes after starting the bot
idk, it just freezes, even the cursor isnt blinking
okay so it's not responding to ,jsk py await _ctx.invoke(_bot.get_command('bad'), words="act2 b2b") in the server but it is in DMs (it then fails bc of the db call's ctx.guilbut the print statement's send the ouputst Input: act2 b2b Bad Words: ['a', 'c', 't', '2', ' ', 'b', '2', 'b']but I don't want each word split into individual chars so I'm assuming my for looppy for word in words: bad_words.append(word) is not the way to do it and i should instead be splitting the string on " " (I have some inputs that include whitespace so I'd need to wrap each input in a char I can split the input on
nothing
ok
hello anyone. any idea how to add slash commands correctly? im lost right now having never used slash commands before. pls ping when you respond
no errors
your bot does have permissions to use slash commands right? as well as the person who is trying to use the command having slash command perms
so i want to make a role giver by command how would you make it so they can pick one out of a number of 13? using the role name
so your suggesting i try and re-invite it to my server?
that might fix it, i'm just asking if it has the slash command permission on it's role (you could add this manually i guess) and you use need the application.commands scope in your bots oauth
it has administrator perm in my server
did you give it both of these scopes when you first made it's invite link? if not remake the invite link and invite it again (you won't need to kick it before inviting it bc reinviting it will just update it's permissions)
thx so much that works. never knew thats what scopes were for! youve been a huge help
np, yeah before slash commands were added all you needed was the bot scope (which is what most guides online will say) but when slash commands were added discord also added (or actually made use of) applications. commands which is specific to giving your bot slash commands
cool, didnt know that until now
making an eightball command, how do i make it give an error when there's no context? i tried this:
async def eightball(message):
responses = ["As I see it, yes.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.",
"Don’t count on it.", "It is certain.", "It is decidedly so.", "Most likely.", "My reply is no.", "My sources say no.",
"Outlook not so good.", "Outlook good.", "Reply hazy, try again.", "Signs point to yes.", "Very doubtful.", "Without a doubt.",
"Yes.", "Yes – definitely.", "You may rely on it."]
if message is None:
await message.channel.send(f"say something")
else:
await message.channel.send(f":8ball: {random.choice(responses)}")```
hello again, i want to make a role giver command for example &giverole examplerole and the same command could give multiple roles per their selection do you know where i can start?
is this giving you any error's? you don't appear to even be passing in context
Well now message is ctx
Since it's the first argument
i replaced message with ctx
not that i'm trying t spoon-feed (can't remember if there's a rule for that here) but i think your looking for something likepy @client.command() async def eightball(ctx, message: str = None): responses = ["As I see it, yes.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don’t count on it.", "It is certain.", "It is decidedly so.", "Most likely.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Outlook good.", "Reply hazy, try again.", "Signs point to yes.", "Very doubtful.", "Without a doubt.", "Yes.", "Yes – definitely.", "You may rely on it."] if message is None: await ctx.send(f"SAY SOMETHING!") else: await ctx.send(f":8ball: {random.choice(responses)}")
message will also never be None
So having that if statement is useless
Let's rewind, what are you trying to do
8ball command
Then why are you checking the message

You don't have to go through any if statements. Just send your message
bruh
If the variable is never going to be used, why?
There is 0 reason to take a message argument
do you know what an 8ball command is
I think you're the one not understanding
I think what they are trying to do is the user provides a input, message then the bot shows a response for their message also that’s how, 8th ball works
But they're not using the variable?
because it doesn't have to be used, but it has to be there
They are trying to show the user that a message was imputed
set a default value to the message argument by using message = None
But they're not
Mhm
They're not using the variable
in your command definition
how do you change a roles place in the role heirarchy?
ok
yeah that's what I was thinking (although this isn't my command 😄)
because if you don't do that, without the message, you'll get an error
How would the user know their question was inputted if it was never repeated back?
please stop and try helping the person
I am helping them. You're one the who started this
sure
If you don't like it, don't continue
now I'm gonna end it
Simple

delayed realization

because their question would still be in chat (presumably) bc at no point does the bot delete their msg. yeah most 8ball commands also include the question aksed but that doesn't mean it needs to be included in the final response
and now i'm backing off 
How would removing the message argument prevent the user from knowing if their answer was inputted
cuz it would work even if he doesn't put a question
yeah was about to say that
How so?
wdym how so
and even if he puts a question, the bot gets a too many arguments error
it would only work without a question
!e
def hello(first, second):
print(first, second)
hello("hello", "world", "!")
@cold sonnet :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | TypeError: hello() takes 2 positional arguments but 3 were given
well not that's it's my command but I seem to be investing in it's success now. here's the latestpy @client.command() async def eightball(ctx, *, message: str): # message is required to be inputted, if no message is given then the command fails with a invalid arg error (I think) responses = ["As I see it, yes.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don’t count on it.", "It is certain.", "It is decidedly so.", "Most likely.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Outlook good.", "Reply hazy, try again.", "Signs point to yes.", "Very doubtful.", "Without a doubt.", "Yes.", "Yes – definitely.", "You may rely on it."] await ctx.reply(f":8ball: {random.choice(responses)}")I used reply so that the user knows that the bot is responding to their invocation not someone else's (since someone mentioned something along those lines)
No
I just tested it
There is no such error thrown
you will
idek
you will?
I just tested it. It doesn't throw an error
how do i ignore the missing permissions for sending a message error?
how would it not raise and error
¯_(ツ)_/¯
Alright so I was right. There is no reason to add a message variable in the 8ball command
Literally just an unused variable
tho it makes more sense
It doesn't make any sense
only if you want to list the question in the answer
it does for visualisation
The user did not
What?
..
because he wants the bot to only answer when getting a question
im not are you ok?
so it's not even unused
Then check if the message content is only <prefix>8ball
Simple
kaya going mad 😳
so you just called another attribute to get a variable, same memory usage
its how python works?
@silver magnetsorry for ping but does this match what your looking for? you could make it message: str = None if you want the command to respond when no question is asked but with that code it's making message a required part of the command. the * is making it take the full string input rather than just the first word
Anyone got anything to say to contradict me then please explain
if you give more arguments to a function it will raise an error how wouldnt i be confused thats just unpythonic?
okimii just test it yourself. I did and it throws no errors
you stole my fucking gif
well, not my gif
🏃
but I used it
Okay now back ontopic
I guess discord-bots is gonna be another warzone
whos kaya
This always happens
the guy in blue i guess
Get some popcorn and watch
mhm
its basic python
already did
guys
dunno
I got fizzy drinks
LOL
lol
could I have python bot on my own server?
useless ping i see no reason why
Hello, what's the issue?
can't see why not
link of the bot?
Look, I don't want to argue with you but it doesn't throw any errors. Just test it yourself
someone pinged you.
to code in my own
yes but thats just the library?
You'll have to clone the github
?
show me
!src
arguments are my favorite thing to watch
huh
that link?
Bot is down
it got upset about your argument
oh yeah
Let's keep this channel on the topic of Discord bots please 🙂 This isn't off-topic.
too much bans for one day 🥱
Do you want THE python bot in your server or A python bot in your server?
lol
!help
...
@final iron you lied to me
It was online ok?
😠
They must have fucked with src code and broke something
@unkempt canyon
hey
hi
have I got this compact if statement correct?py guild = 448405740797952010 if ctx.guild.id is None else ctx.guild.idI'm like 95% sure it is
just do
guild = 448405740797952010 or ctx.guild.id
it will always be the id first
https://stackoverflow.com/questions/26454624/renaming-a-file-in-pycharm I'm gonna ruin this mans whole career
number*
yeah true
ctx.guild.id or 448405740797952010
how do i write multiple lines for a command
How does this relate to Discord bots? 
if I was gonna do that then I'd need to flip them but is my if statement correct regardless?
i have smth related to discord bots
how do i write multiple lines
for me i cant seem to write more than one line for a command
yay, I don't do many compact if statements and when I do they tend to be rather complex for my little brain to figure out but i am getting better at them
you can use \n to make a new line
so...basically it's on stack overflow. If it's on stack overflow, it's where people ask questions relating to coding, including discord bots. So...it technically is related to discord bots
thats probably the description kwarg with bold titles
could you show an example?
!e
print("Line1\nLine 2")
>>> print("hello \nworld")
hello
world
!e
print("hello\nworld")
the bot died

Yikes
the bot committed death
Thank you
Not sure what you mean sorry. Could you give us a better idea?
THE python bot the one I say !code
and i can code and show my code to others
nope.
it's only for python discord server
huh 😦
Well, when I write a command, say something like this
You would have to clone the github then
Oh @fluid yarrow, are you looking for a bot you can use to run code from a message and see the output?
is there a command that i can code in my own server?
the link in github
kinda
This is result I get. What do I do if I wanted to have multiple lines for description?
this?
Yeah
If you wanted specific commands you could just copy the code/file
One thing though. If you're looking for an eval command then it would be a bit complicated as you would have to setup your own snekbox server
That's the main bot we use in this server. It's quite tailored to the needs of this server however, so it isn't suitable for running in other servers. The code is under an MIT license, you your welcome to use parts of it.
The !eval command uses another service called SnekBox.
i dont need eval
just a thing to underline a cod
classic !code
then ''' ecc
not necessarly to use the output
so to sum up, what should I do for my needs
So, when a user uses this command, what do you expect to happen?
We have a !code command in this server, which just instructs people on how to use code-blocks in their messages.
These things:
```py
hello world
```
Is that what you were thinking of?
YEAH
Wouldn't you just send a message containing that then?
underline ecc?
Well you can create codeblocks with python syntax highlighting like so:
```py
stuff
```
Is that what you mean?
why doesnt it highlight then
You're most likely missing the py part
for i in range(5):
# stuff
It does highlight, functions are red, keywords are green, comments gray etc
Hi so I have these lists as part of a command for my discord bot.py db_list = ["glitch", "toffee"] words = ["act2", "b2b", "act 2", "glitch"] bad_words = [] bad_words.append(db_list) for word in words: bad_words.append(word)I have db_list hard coded for this example but it would normally be fetching these from the database. and i also hard coded words but normally these would be a string of words provided in the command async def bad(self, ctx, *, words: str): What i want to happen is for my bot to make a new list (bad_words) and append everything from db_list into bad_words. I then want it to append each word from the words string onto the bad-words list. Currently it is splitting each word in words into individual chars but I don't want that so I'm guess I need to split the string on a character and I want to use , as some of the inputs of words might contain blank spaces.
!e ```py
db_list = ["glitch", "toffee"]
words = ["act2", "b2b", "act 2", "glitch"]
print(db_list + words)
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
['glitch', 'toffee', 'act2', 'b2b', 'act 2', 'glitch']
why?
Since lavalink violates youtubes ToS
So I have this Discord bot idea and I want to have it use Roblox API but I don't know the best library for Roblox API. Anyone have ideas?
yeah! that solves one question thanks. next question is about splitting the words string input into individual words rather than one long long string as py for word in words: bad_words.append(word)doesn't work for my use case, would it be words.split(",")? and I'd need to save that to a list variable as well so how would i do that? also how can i remove duplicates the lists?
i didn't even know roblox had a api
Yeah it has some API I found like 2: [robloxpy, roblox ]
But i dont know which one is better
it does
I think I'm in their server somewhere
oh wait nvm I'm not
Robloxpy has a site that tells all the functions and stuff you can do
Also, How would I send an Image from the bot to discord?
uhm what do you mean words.split(",") doesn't work? can i get an example string and what you expect
oh I don't mean words.split(",") doesn't work (I assume it does right?) but the following for statement doesn't workpy for word in words: bad_words.append(word)
you'd have to convert it to a file then do await ctx.send(file = image_file, files = list_image_files)
I have no clue on what you want to do here.
Thanks!
Oh you want to convert everything into a string?
taking it from the toppy db_list = ["glitch", "toffee"] words = ["act2", "b2b", "act 2", "glitch"] bad_words = [] bad_words.append(db_list) for word in words: bad_words.append(word)
- I have
db_listhard coded for this example but it would normally be fetching these from the database. - hard coded
wordsbut normally these would be a string of words provided in the commandasync def bad(self, ctx, *, words: str):
~~3) What i want to happen is for my bot to make a new list (bad_words) and append everything from db_list into bad_words. ~~ Done via bad_words(some_list + db_list
- I then want it to append each word from the
wordsstring onto thebad-wordslist.
Currently it is splitting each word in
wordsinto individual chars but I don't want tha.t
- I guess I need to split the string on a character and I want to use
,as some of the inputs ofwordsmight contain blank spaces.
I'm thinking
some_list = words.split(", ")would work?
Bot is dead
oof
@flat solstice anyways i still have no clue on what we are splitting now
Oh you mean you want to make a cmd that takes in those words?
ik, I don't want to split a list (I don't think 🤔). I made words = ["act2", "b2b", "act 2", "glitch"] a list in my example but the command accepts it as a stringpy async def bad(self, ctx, *, words: str): and so I need to split that string,
okay glad i was able to explain my brains weird half formed idea
so does what I'm trying to do make sense? and if so would some_list = words.split(", ") be the way to do it as I do need a list of the words after it splits them out of the string
!e ```py
s = "act2,b2b, act2,glitch,glitch, b2b"
db_list = ["glitch", "toffee", "act2"]
words = s.replace(" ", "").split(",")
print(set(db_list + words))
worth the try
Depends if you want to fully disregard spacing yes or no
never.
!d defaultdict
Your effort has been nice
some of the input words might contain spaces, which is why I want to split it on ,, does that answer the question sufficiently
bot is down
Best to check if there is a leading space
!e ```py
s = "act2,b2b, act 2,glitch,glitch, b2b"
db_list = ["glitch", "toffee", "act2"]
words = [w[1:] if w[0] == " " else w for w in s.split(",")]
print(set(db_list + words))
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
{'act 2', 'toffee', 'b2b', 'act2', 'glitch'}
🥳
thanks for the help
zip(*iterables, strict=False)```
Iterate over several iterables in parallel, producing tuples with an item from each one.
Example:
```py
>>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
... print(item)
...
(1, 'sugar')
(2, 'spice')
(3, 'everything nice')
```...
Thanks
!ping
You are not allowed to use that command here. Please use the #bot-commands channel instead.
what would this do if db_list was empty? would iy just not add that on or would it fail to combine them?
hooray bot is fully functioning
What is 5 + 0?
You know the answer, it's still 5, pretty sure it doesn't crash.
Why not just w.strip()?
What does strip do?
str.strip([chars])```
Return a copy of the string with the leading and trailing characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or `None`, the *chars* argument defaults to removing whitespace. The *chars* argument is not a prefix or suffix; rather, all combinations of its values are stripped:
```py
>>> ' spacious '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
``` The outermost leading and trailing *chars* argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in *chars*. A similar action takes place on the trailing end. For example:
cap
noob
report
gets banned

Okay but do you have lasagna in your oven?
Anyway, I'm adding a welcome card feature to my bot. What's the best way to protect my bot from freezing since pillow isn't async
Just run it in executor
Oh yeah
I'm sure most people do that for pillow
I forgor
The executor is the concurrent.futures.Executor or something else?
!d asyncio.loop.run_in_executor
awaitable loop.run_in_executor(executor, func, *args)```
Arrange for *func* to be called in the specified executor.
The *executor* argument should be an [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor "concurrent.futures.Executor") instance. The default executor is used if *executor* is `None`.
Example:
Whats the issue here
You have embed command somewhere it seems
You named your variable embed1 then tried to set embed's image
Own api
What about run_in_executor?
how do i fix it
Set embed1's image?

well you could also just create a task no need for an executor.
hmm wait
Task?
Like discord.py's tasks or something else?
Asyncio task ig
!d asyncio.get_running_loop
asyncio.get_running_loop()```
Return the running event loop in the current OS thread.
If there is no running event loop a [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised. This function can only be called from a coroutine or a callback.
New in version 3.7.
!e
import asyncio
async def stuff():
print(10 ** 5)
async def main():
task = asyncio.create_task(stuff())
await task
asyncio.get_event_loop().run_until_complete(main())```
okay so moving on from my string stripping. I have this function call which is getting data from my dbpy data = await self.bot.get_data(448405740797952010 if ctx.guild.id is None else ctx.guild.id) and it keeps throwing this error when used in DMspy ddata = await self.bot.get_data(448405740797952010 if ctx.guild.id is None else ctx.guild.id) AttributeError: 'NoneType' object has no attribute 'id'so I triedpy data = await self.bot.get_data(ctx.guild.id or 448405740797952010)and got the same error so i removed ctx.guild.id just to see if something else is broken and got this errorpy bad_words = (set(data[28] + words)) TypeError: unsupported operand type(s) for +: 'NoneType' and 'list'
@vale wing :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:11: DeprecationWarning: There is no current event loop
002 | 100000
!d asyncio.loop.create_task
loop.create_task(coro, *, name=None)```
Schedule the execution of a [Coroutines](https://docs.python.org/3/library/asyncio-task.html#coroutine). Return a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") object.
Third-party event loops can use their own subclass of [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") for interoperability. In this case, the result type is a subclass of [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task").
If the *name* argument is provided and not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").
Changed in version 3.8: Added the `name` parameter.
This?
Yeah
In DMs ctx.guild is None
yeah so if it's none shouldn't it then use the provided ID?
I mean you have the condition put wrong
You can't access any attributes of the None as it doesn't have any
#instead of this
if ctx.guild.id is None
#do this
if ctx.guild is None```
import rin
class CommandDemo(...):
# Some implementation here
...
rin.export(type=rin.AppCommand.MESSAGE, entry=CommandDemo)
``` thoughts?
This would be in a separate file, which the main file then hooks onto
can I say my thoughts are no
Reasons for it
absolutely not
andy being different for the sake of being different
@pliant gulch give me advantages of this opposed to cogs/normal implementation
this is supposed to delete non-english messages, but im getting an error
def isEnglish(s):
try:
s.encode(encoding='utf-8').decode('ascii')
except UnicodeDecodeError:
return False
else:
return True
@client.event
async def on_message(ctx, message):
if isEnglish(message.content):
pass
else:
await message.delete(message)
delete_em = discord.Embed(title=f"Message Deleted.", colour=0x2c1945)
delete_em.add_field(name="Reason:", value=f"Not-English Message", inline=False)
delete_em.set_footer(text="https://github.com/zoaq1")
await ctx.message.channel.send(f"{ctx.message.author.mention}", embed=delete_em)
Keeps your main file clean, more room to do things. Bound methods to callback, class dependent caching, built-in setup & teardown methods, syncing methods, overall cleanliness
on message only takes one param
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
but how do i send message with ctx
Note, this isn't even a Cog implementation..
message has a channel attr which channel has a .send method
so it should work without ctx?
yes
do you have to register each command with .export? how does it keep main files clean? is there some documentation for this
this too
TypeError: Message.delete() takes 1 positional argument but 2 were given
well it says it?
but message.delete only gives 1 argument
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
examples/example_custom_event.py line 31
@client.on(CUSTOM_MESSAGE_CREATE)```
#help-cherries if someone could help pls
whats message.custom
oh shit
im blind
ignore thy
it forces the message into the typehint?
No I plan on allowing multiple entry points, and it would keep the main file clean from large slash commands. Imagine a slash command in your main runner file with 50 subcommands
ohhh so i didnt need the arguement, thanks
yw
Nope, it uses the event literal
Errr used to be a literal enum, now it's a class instance with a cache
Allowing client-less events
Somewhat*
You can wait-for without client, register without client, etc but a gateway connection is still needed
Intellectuals who enjoy strongly typed code
hmm
#help-cherries plsssss
this dude
Also rin has some cool syntactic sugar
We got collectors, one time event dispatches, collectors with timeouts
Cool stuff
Also concurrent requests, compared to discord.py
the one time event dispatches is nice
seems like ive got a lot to learn
whelp
sleep makes the mind strong
off i pop
I know right brandy
how would i catch the exception for missing permissions of bot role? what i have now isnt working.
except discord.errors.Forbidden:
error handler of discord.py should catch it
it says this but thats what i put
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
Yeah i recommend a on_command_error
mb i need example
im not using cog 😭
I don't know where I went wrong:
import disnake
from disnake.ext import commands
import os
from dotenv import load_dotenv
load_dotenv()
token = os.environ["bot_token"]
bot = commands.Bot()
@bot.event
async def on_ready():
print(f"Logged in as {disnake.user}.")
bot.login(token)
token.env
bot_token=token
I get this:
~/artemis-mk2 $ python3 main.py
Traceback (most recent call last):
File "/storage/emulated/0/coding/python/artemis-mk2/main.py", line 7, in <module>
token = os.environ["bot_token"]
File "/data/data/com.termux/files/usr/lib/python3.10/os.py", line 679, in __getitem__
raise KeyError(key) from None
KeyError: 'bot_token'
~/artemis-mk2 $
It worked before I accidentally deleted my code
So idk why it isn't working now
import disnake
from disnake.ext import commands
import os
from dotenv import load_dotenv
bot = commands.Bot()
@bot.event
async def on_ready():
print(f"Logged in as {disnake.user}.")
client.run("token")```
this should work
how can i send a message when my bot joins a server?
when your bot JOINS a server?
yes
no clue
it joins then says hi
best bet would be to make it send something on ping
good idea
^^^^^
i sent fixed code above
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
thanks
Doesn't work, says token isn't defined because it isn't
It hasn't loaded the dotenv file
Meaning it doesn't have the token variable
rename token.env to .env
Am I not able to have it called token.env?
can I have 2 on_message listeners in the same cog?
call the file just .env
You should be able to as long as it's a listener
@commands.Cog.listener()
async def on_message(self, message):
``` two of these
Yeah should work like you'd expect
No prob
how can I have a gui control my discord bot? I just need an area to get directed in
Could be difficult since I'm not aware of any GUIs that are async
currently im using tkinter, dont know how im going to use multi threading to do that
You might able able to have some sort of websocket connection from discord bot to your tkinter
ah multi threading
you would need to get inter-thread communication (if that's the right term)
ok thanks, ill try to work on that
okay so just replace the word ‘token’ with your bot token, i’m not understanding what the issue is
and if you’re trying to use a secret thru replit just create the secret name the top part whatever u want, then the second part put the token
client.run(os.getenv(""))
Well obligatory but you should consider not using replit
but if you must it's probably easier to just put it in as a string
But repl.it has public codespaces, so if you put your token as a raw string instead of getting it through getenv you will be leaking your own token
except you can change it to private very easily
and i use replit because i can’t run my pc 24/7
Okay, so I have a selfbot for fun because why not (started a new one)
Everytime I try to make a embed and send it, it returns a 400 saying it cannot send a empty messages
Did discord patch selfbot or something?
Aware of TOS by the way, i'm not using it maliciously
how can i check if my json database has already 1 thing "inside" the guild id?
if len(add_channel[str(ctx.guild.id)]) == 1:
em = discord.Embed(title=" Antinuke Error!", description=f"{channel} Is currently set for the antinuke logs!\nType: `{p}Antichannel Remove` To remove the channel!", color=discord.Color.red())
await ctx.send(embed=em)
return
that's just checking wrong
i can remove the channel because the command is going to ignore that even tho it returns
it's fucking my brain literally
wait
is not going to remove even tho it says successful
what the fuck
i think its > 2 or sum idk i havent coded in a year 💀
i tried 
oh
well regardless of your intentions selfbots are against TOS
so we can't really help you fix your selfbot
Aren't private codespaces in repl.it a subscription plan only thing?
without using it as parameter
Did you store the ID?
Then you can just do either get_channel() or fetch_channel()
Why not just store the ID w/o the <#>?
i tried using
but because channel is a required parameter
and is already a str
idk how to add the id only
you can store strings
Alr
how are you defining channel?
async def add(self, ctx, channel):
and that's a command?


