#discord-bots
1 messages Β· Page 1149 of 1
π§
π§
π§
File "C:\Program Files\Common Files\System Bot\Bots\welcome\welcome.py", line 57, in on_member_join
asset = member.avatar.with_size(1024) # This loads the Member Avatar
AttributeError: 'str' object has no attribute 'with_size'
it came with this error this time
avatar is a string
π§
what library are you using? and what's the version?
dk if I should ask this
My discord presence extension never works
Like I have to mess with some things in it
And re open my vsc
for vscode?
Yah
ctrl+shift+p, reconnect to discord
Download discord rich presence
Extension
Please help me with this error console disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: text/html', url=URL('https://neelpatel05.pythonanywhere.com/element/atomicnumber?atomicnumber=16')
i scroll up and i see this
join usπ§
how can i check the library version?
help
python 1.7.3
what cult have you started now 
avatar_url_as should have worked then...
try ```py
pip install -U discord.py
2179 omg
π why no cogs
discord.py 1.7.3, python 1.7 was probably released in the 90s
my bad xd
thanks for the idea, ill try python 1 today
i saw a video on that, they dont even have the os module, or random
!pip disco this may work mb
what the heck
this
lol
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destinationβs message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
nice
i have problem with my -balance command
This is the Code:
async def create_balance(user):
async with bot.db.cursor() as cursor:
await cursor.execute("INSERT INTO bank VALUES (?, ?, ?, ?)", (0, 100, 500, user.id,))
await bot.db.commit()
return
async def get_balance(user):
async with bot.db.cursor() as cursor:
await cursor.execute("SELECT wallet, bank, maxbank, user FROM bank WHERE user = ?", (user.id,))
data = cursor.fetchone()
if data is None:
await create_balance(user)
return 0, 100, 500
else:
wallet, bank, maxbank = data[0], data[1], data[2]
return wallet, bank, maxbank
@bot.command(aliases=['bal', 'b'], description="View a users balance")
async def balance(ctx, member: discord.Member = None):
if member == None:
member = ctx.author
wallet, bank, maxbank = await get_balance(member)
embed = discord.Embed(title=f"{member.name}'s Balance")
embed.add_field(name="Wallet", value=f"`{wallet}`")
embed.add_field(name="Bank", value=f"`{bank}/{maxbank}`")
await ctx.send(embed=embed)
And this is the error:
Ignoring exception in command balance:
Traceback (most recent call last):
File "/Users/sgolis/PycharmProjects/Discord_Bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/Users/sgolis/PycharmProjects/Discord_Bot/main.py", line 69, in balance
wallet, bank, maxbank = await get_balance(member)
File "/Users/sgolis/PycharmProjects/Discord_Bot/main.py", line 97, in get_balance
wallet, bank, maxbank = data[0], data[1], data[2]
TypeError: 'coroutine' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/sgolis/PycharmProjects/Discord_Bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/Users/sgolis/PycharmProjects/Discord_Bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/Users/sgolis/PycharmProjects/Discord_Bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'coroutine' object is not subscriptable
/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/asyncio/events.py:81: RuntimeWarning: coroutine 'Cursor.fetchone' was never awaited
self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
data = cursor.fetchone()
and the exception is telling you that data is a coroutine
but idk what coroutine is
!async-await
Concurrency in Python
Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio library, which is included in the Python standard library.
This works by running these coroutines in an event loop, where the context of the running coroutine switches periodically to allow all other coroutines to run, thus giving the appearance of running at the same time. This is different to using threads or processes in that all code runs in the main process and thread, although it is possible to run coroutines in other threads.
To call an async function we can either await it, or run it in an event loop which we get from asyncio.
To create a coroutine that can be used with asyncio we need to define a function using the async keyword:
async def main():
await something_awaitable()
Which means we can call await something_awaitable() directly from within the function. If this were a non-async function, it would raise the exception SyntaxError: 'await' outside async function
To run the top level async function from outside the event loop we need to use asyncio.run(), like this:
import asyncio
async def main():
await something_awaitable()
asyncio.run(main())
Note that in the asyncio.run(), where we appear to be calling main(), this does not execute the code in main. Rather, it creates and returns a new coroutine object (i.e main() is not main()) which is then handled and run by the event loop via asyncio.run().
To learn more about asyncio and its use, see the asyncio documentation.
ok but how can it fix my problem?
you need to await it man
read the tag lol
it literally says in the error you sent
coroutine 'Cursor.fetchone' was never awaited
How to install discord.py the latest version using pip ?
pip install -U discord.py
unless by latest you're referring to the master branch?
Too slow.... π
I don't believe that.
there was some github command
so... the master branch?^
that's for discord.py 2.0, not the stable version.
pip install -U git+https://github.com/Rapptz/discord.py
cls
where did powershell go π
microsoft made it a paid software now 
Still alive and kicking, just not really as much.... Unless your lucky like me looking after Windows based infrastructure...
And it made curious, I thought I was running 2.0 but after the convo just now, I realised I ain't so will do an upgrade later.
Is it worth it? Or is 1.7.3 fine to sit on?
1.7.3 will anytime stop working..
Cheers, better upgrade after work then just so I dont get hit with that.
its better to start refactoring your code rn so it won't be a ton of rewrite work for later.
Yeh, true, considering I am still pretty much at the beginning too.
(ngl, still stuck on my wait_for block) so yeh it won't be a big problem to rewrite π
Possible to do something like
if ctx.author is client.owner: do stuff ?
Rather than using @fresh banemands.is_owner
Uh-
!d discord.ext.commands.Bot.owner_ids
The user IDs that owns the bot. This is similar to owner_id. If this is not set and the application is team based, then it is fetched automatically using application_info(). For performance reasons it is recommended to use a set for the collection. You cannot set both owner_id and owner_ids.
New in version 1.3.
you can if ctx.author.id in bot.owner_ids
Iβm in a cog
So should I use self.client?
I mean owner_id would work in the cog right?
why wouldn't it? its the same thing, just inside a Cog
yes
like self.client.owner_ids or self.bot.owner_ids
why do we need cogs π
i forgor
messages = await ctx.channel.history(limit=10, oldest_first=True, after=after_date).flatten()
can i do dis
chanl = bot.get_channel(id)
mes = await chanl.history(...)
you don't need cogs, but it's useful for making your code readable and not making it a 5,000 line mess
https://mystb.in/ExecutiveCarriedLinking.sql I have this error for** 3 days** I can't take it anymore what should I do to download discord 2.0
Cogs = easy to manage and clean code
Cogs also helps in help commands
For category
I get this error, but I don't know what it means, can someone help me?
st_charge() takes 1 positional argument but 2 were given
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\pyrogram\dispatcher.py", line 240, in handler_worker
await handler.callback(self.client, *args)
TypeError: st_charge() takes 1 positional argument but 2 were given```
It means that function only has 1 parameter but you're passing two arguments to it
def foo(i):
return i
foo(1) # fine
foo(1, 2) # passing 2 arguments, not fine
Which library should i use? Tell me any name
Source code: Lib/difflib.py
This module provides classes and functions for comparing sequences. It can be used for example, for comparing files, and can produce information about file differences in various formats, including HTML and context and unified diffs. For comparing directories and files, see also, the filecmp module.
for what?
The comamnd thing the example you have me
Yeah this
Is it a library?
bruh
what else can it be
Type of snake
diff -> difference
its also a language/utility
How to fix this error?
you need to check on the names, not the command object itself.
I not able to understand what you Mean
I had it preinstalled on my win11
async def p(ctx, user : discord.Member == None):
if user == None:
user = ctx.author.id```
what part?
that was a joke. ofcourse.
The check names
discord.ext.commands.errors.MissingRequiredArgument: user is a required argument that is missing.
@bot.listen("on_command_error")
async def error_handler(ctx, error):
comlist = []
for command in bot.commands:
comlist.append(command)
invoked_with = ctx.invoked_with
matches = difflib.get_close_matches(invoked_with, comlist)
await ctx.send(f"do you mean {matches}?")
Here is code
comlist is a list of command objects, it should be a list of command names instead...
How can I do that?
==?
!d discord.ext.commands.Command.qualified_name
property qualified_name```
Retrieves the fully qualified command name.
This is the full parent name with the command name as well. For example, in `?one two three` the qualified name would be `one two three`.
!list-comp
Do you ever find yourself writing something like this?
>>> squares = []
>>> for n in range(5):
... squares.append(n ** 2)
[0, 1, 4, 9, 16]
Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:
>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]
List comprehensions also get an if statement:
>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]
For more info, see this pythonforbeginners.com post.
you would be ```py
[ command.name for command in list_of_command_objects ]
I have an odd feeling he's making a help command without subclassing
read above
oh yeah i didn't read above sorry
how can I check if ctx.guild.channel is mentioned in ctx.message.content?
this is parameter right?
ye
yes
id, mention etc
I can explain for what i need it so u can understand
is there a parameter for time?
like 10s
or 10d 2h 5m
I'm trying to create giveaway command
no
no, create a Converter yourself
you have to parse it your own
zbrt
Ok
There's https://dateparser.readthedocs.io/en/latest/ of you want fuzzy matching
you can check if <#channel_id> is in message.content
@bot.event
async def on_command_error(ctx, error):
if isinstance(error,CommandNotFound):
comlist = bot.commands
comlists = [ command.name for command in comlist ]
invoked_with = ctx.invoked_with
matche = difflib.get_close_matches(invoked_with, comlists)
embefk = discord.Embed(title=f"did you mean?", description=matche,color=discord.Color.yellow())
embefk.set_thumbnail(url='https://media.discordapp.net/attachments/969254133779558410/997473128395587634/images.png')
await ctx.send(embed=embefk)
It's returning empty list ;
Hmm
I still confused
what variable is giving you an empty list....?
comlist = bot.commands
this is an iterable
comlists = [ command.name for command in comlist ]
this is an iterable too
matche = difflib.get_close_matches(invoked_with, comlists)
and this too
which one are you talking about??
Matche
print comlists and print invoked_with then see if you a matching string in them or not
you might want to adjust the cutoff as well
Ok
I printed and it's working fine it loaded all comannds but not 2 commands even i have ev loaded that cog
Can you help pls
why not just help here 
Which privacy π
wdym by "handlers code"? can you elaborate?
error handling?
if I do !check <word> it checks my txt file for that name then says Found
How do I do that
if msg.startswith("val") or msg.startswith("Val") or msg.startswith("VAL"):
```is there a way to apply `.lower()` to this so i dont have to verify each case
if message.content.lower == βvalβ:
Your code
have to add the () no?
if message.content.lower() == βvalβ:
Iβm on mobile atm, let me go look at my code rq
its startswith cause therell be arguments too btw
i mean i can test
message.content.startswith.lower() == 'val'
```i hope that works
Bruh there is slowmode on here
Guys i need help can anyone?
so?
@bot.event
async def on_command_error(ctx, error):
if isinstance(error,CommandNotFound):
comlist = bot.commands
comlists = [ command.name for command in comlist ]
invoked_with = ctx.invoked_with
matche = difflib.get_close_matches(invoked_with, comlists)
if not matche[0]:
matche = "command not found"
else:
matche = matche[0]
embefk = discord.Embed(title=f"did you mean?", description=matche,color=discord.Color.yellow())
embefk.set_thumbnail(url='https://media.discordapp.net/attachments/969254133779558410/997473128395587634/images.png')
await ctx.send(embed=embefk)
It's comand intelligence but it not takes 2 comannds in it's list even i ahve loaded all cogs
Anything like guild.created_at?
im tryna get bad apple on discord and all of a sudden i get this, can someone help me?
!d discord.Guild # See by yourself
class discord.Guild```
Represents a Discord guild.
This is referred to as a βserverβ in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guildβs hash.
str(x) Returns the guildβs name.
someone help me pls
just fyi, the question is off topic
and read the error

I saw
im just a dumbass with some technology
ik theres permission denied
but im too damn dumb to Understand
cool
you didnt specify the file type and on windows when you have the file opened and then you try to open it in ur code, it raises that error
hmm how fix this π€
my bot not send any message
https://mystb.in/HydrogenSpecificallyPrecise.python
how do i make something scan all messages for blacklisted texts and delete them?
for example:
!scan
Bot - 7:39
Found 4 blacklisted texts!
Josh - Bitc
GURLLL - Amogus
GURLLL - Amogus
TanGt - Gay
you don't call any function, so its not going to send anything
uhm you can make an example ??
in python, the function body is not executed until you call the function unlike other languages
def foo():
print('hello')
# it doesn't print 'hello'
foo() # this prints 'hello'
` i = random.randint(0,5)
switcher={
0:zero,
1:uno,
2:due,
3:tre,
4:quattro,
5:cinque
}
func=switcher.get(i)
return await func()`
this not work?
get the messages using channel.history() then look for it in there
its a folder
this is the function
async def cinque():
file = discord.File("/home/py/Desktop/TelSpin/TelSpinGif/TelSpinYellow.gif")
e = discord.Embed()
e.set_image(url=("attachment://TelSpinYellow.gif"))
await ctx.send(file = file, embed=e)
return 'cinque'
i = random.randint(0,5)
switcher={
0:zero,
1:uno,
2:due,
3:tre,
4:quattro,
5:cinque
}
func=switcher.get(i)
return await func()
this function is never called so body doesn't get executed, and you did return 'cinque' so any code under that will not execute because return exits the function
you can't open a folder, what are you trying to do?
Don't think open works for folders at all
Maybe try os.listdir or something similar
!e
import os
print(os.listdir('.'))
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
['requirements', 'config', 'user_base']
and now its leading to 1 error left
use that if you want to get all files in the directory
is dpy
import discord
or import discord.py
I need a custom bot
Make one
bro solved world hunget
π
ah ok
i dont have food
"then eat"
How can I make a chatbot without ml? In dpy
thats you exenifix
Yeah so what
what feature should it have?
idk lmao
Who tf is gonna make a bot for someone here
yea
It should talk like we talk with our friends and it can do some things like good assistant
tbh
Add some keywords and response to keywords nltk is ok
and its against rules to try to get people to do it
i have a question for discord bots
just get on fiverr if you want one duh
is playing bad apple (music video btw) frame by frame with 15 bots to avoid rate limiting api abuse?
I'd say so
FUCK
thanks
oh 15 bots, i thought 15 fps for some reason
lmao it got 10 fps actually
im not looking for even worse rate limit bro
higher means more messages (edits) per second
ohh
oh and uhh
im confused but uh
i saw someone post bad apple on discord messages in real time
should i report them
if they respect the rate limits it's fine
if they don't they will end up getting rate limited with the time so no need to do anything
but they said "this is api abuse, however there where no spikes on discord api status"
idk what to think at this point
a single bot would definitely not affect the overall api status
still need more power than that
but yeah if ya want you can report to discord, don't know if they take any actions on that
i once reported an underage kid 4 times
because they kept making new accounts
and keep using vpns
and discord cared
so maybe they can care about that too
dunno
that's just bypassing the api rate limits
you'll probably end up using the same IP
and your ip will just get banned
bascially what usually happens with bots hosted on replit
ips are shared among multiple users
they all host their bot, and get the ip banned
i host my bots with visual studio code
no like
How to create a webhook set itβs avatar and send a message with it via a command
theres run
hosting you do on your computer terminal
docs probably?
but bro i used visual studio code to load bad apple into a png frame by frame
idk what u on rn
Search webhook with those search funv
yeah you still don't host on vsc
Lets not discuss things that can run into rule 5
!d discord.Webhook.avatar
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the webhook has.
If the webhook does not have a traditional avatar, `None` is returned. If you want the avatar that a webhook has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.display_avatar "discord.Webhook.display_avatar").
Is this settable
yeah i mean i dont host full on servers for 3 days
eh? what wouldn't follow ToS here?
Bypassing rate limits
i host it for testing
why not
Well that's what I'm explaining, saying they shouldn't do it
its not like mao zedong is watching me
!d discord.Webhook.edit should be
await edit(*, reason=None, name=..., avatar=..., channel=None, prefer_auth=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits this Webhook.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
ya right, you can't
!rule 5 - Its a server rule
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
you can set avatar while creating the webhook cant you
i was asking a question sooo π
i think you can do it, but if you want to do it for an existing one you need to edit
Does it even have a constructor
Like it should create the webhook then something with it and delete it
you can fetch using its ID
!d discord.Webhook.send
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using the webhook.
The content must be a type that can convert to a string through `str(content)`.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects to send.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
what's the thing for on the bot joining the server
!d help
help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).
This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
on_guild_join
how do i get it to provide me the id's or names of the channels upon joining the guild
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
i want the bot to get a list of the channels and find something like " general " " lounge " then send the help message
it has a guild object
!d discord.Guild.channels gives you list of channel objects ( which includes text, voice, stage and category channels ), utilise it
You can then use guild.channels to get a list of all channels as objects
property channels```
A list of channels that belongs to this guild.
Personally wouldn't do like that, due to channel names being hard coded.
I would loop over all channels and try to send a message in the channel. If it fails, try the next one. If it worked, stop the loop.
Don't recommend using the name
@bot.command()
async def sudo(ctx,member: discord.Member,*,content):
await send(content=content, username=member.name, avatar_url=member.avatar.url)
error:
raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: spin() takes 1 positional argument but 2 were given
!d discord.Guild.system_channel
property system_channel```
Returns the guildβs channel used for system messages.
If no channel is set, then this returns `None`.
names = ["general", "main", "lounge"]
channels = filter(lambda x: any(name in x.name for name in names), guild.text_channels)```
what is send?
Switch the lambda and the list tough.
!d filter
filter(function, iterable)```
Construct an iterator from those elements of *iterable* for which *function* returns true. *iterable* may be either a sequence, a container which supports iteration, or an iterator. If *function* is `None`, the identity function is assumed, that is, all elements of *iterable* that are false are removed.
Note that `filter(function, iterable)` is equivalent to the generator expression `(item for item in iterable if function(item))` if function is not `None` and `(item for item in iterable if item)` if function is `None`.
See [`itertools.filterfalse()`](https://docs.python.org/3/library/itertools.html#itertools.filterfalse "itertools.filterfalse") for the complementary function that returns elements of *iterable* for which *function* returns false.
send from the webhook doc
Sorry I forgor π
what should i use, i can't use ctx ig?
why cant you use a context when you have a context

@bot.command()
async def sudo(ctx,member: discord.Member,*,content):
await ctx.send(content=content, username=member.name, avatar_url=member.avatar.url)
@slate swan
read the error?
username and avatar_url and arent valid kwargs
you need to create an instance of discord.Webhook then do something like webhook_instance.send(...)
send is an instance method, not classmethod, so you can't use it like that
!d discord.TextChannel.create_webhook
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
Requires [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") permissions.
Changed in version 1.1: Added the `reason` keyword-only parameter.
I recommend either keeping it in cache for an hour or something or delete it instantly
@<commands/bot>.command(name="<webhook>")
async def _webhook(<self>, ctx: commands.Context) -> None:
webhook = await ctx.channel.create_webhook(name="uwu")
await webhook.send("uwu", avatar_url="<>")
π₯
π§
Possible to make this a variable and use
webhook = . . .
await webhook.send(. . .)
can anyone help?
yes
great
ash sended it
sended
you are make the string lowercase then comparing it with a capitalized string
i dont understand
how to fix it
lower makes everything lowercase, so if i do 'Ryuga'.lower() it becomes 'ryuga'
so if the message contains 'Hello' then you apply lower to it, it becomes 'hello' but then you are checking if 'hello' == 'Hello' which it is not
make the right side lowercase as well
!e
print("hello".lower())
@slate swan :white_check_mark: Your eval job has completed with return code 0.
hello
https://mystb.in/JonEnclosureProposed.python
``2022-07-15 17:20:32 ERROR discord.ext.commands.bot Ignoring exception in command spin
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 1330, in invoke
await ctx.command.invoke(ctx)
File "/home/pi/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 987, in invoke
await self.prepare(ctx)
File "/home/pi/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 904, in prepare
await self._parse_arguments(ctx)
File "/home/pi/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 811, in _parse_arguments
transformed = await self.transform(ctx, param, attachments)
File "/home/pi/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 663, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: bot is a required argument that is missing.
i added ,bot but i get this
Compare with what you have to the right of your ==
Hey all, I know this is probably a stupid question, but... Is there a way I can combine these two and have them in just a single class?```py
class VoteDropdown(disnake.ui.Select):
def init(self, test: list):
options = [disnake.SelectOption(label=entry.get('label'), description=entry.get('desc'), emoji=entry.get('emoji'), value=entry.get('user').id) for entry in test if entry.get('user') is not None]
super().init(
placeholder="Select one",
min_values=1,
max_values=1,
options=options
)
async def callback(self, interaction: disnake.MessageInteraction):
...
class VoteView(disnake.ui.View):
message: Optional[disnake.Message]
def __init__(self, users, **options):
super().__init__(**options)
self.votes = {}
self.add_item(
VoteDropdown(users)
)
async def on_timeout(self) -> None:
...
@bot.command(name="sudo")
async def _sudo(ctx,member: discord.Member,*,content):
await ctx.message.delete()
e = discord.Embed(title=f"Sudo By {ctx.author.name}", description=f"Ivoker: {ctx.author.name} ({ctx.author.id}) \n \nInvoked on: {member.name} ({member.id}) \n \nContent: ||{content}||",color=discord.Colour.dark_theme())
e.set_footer(text="Please view content on your own risk.")
webhook = await ctx.channel.create_webhook(name=member.name)
await webhook.send(content,avatar_url=member.avatar.url)
chn = bot.fetch_channel(997525777161650306)
await chn.send(embed=e)
webhook works fine but the message isn't sent
await bot.fetch_channel()
You asked for it ```py
class VoteView(disnake.ui.View):
message: Optional[disnake.Message]
def __init__(self, users, **options):
super().__init__(**options)
self.votes = {}
self.votedrop = disnake.ui.Select(
placeholder="Select one",
min_values=1,
max_values=1,
options=[disnake.SelectOption(label=entry.get('label'), description=entry.get('desc'), emoji=entry.get('emoji'), value=entry.get('user').id) for entry in users if entry.get('user') is not None]))
self.votedrop.callback = self.vote_callback
self.add_item(
self.votedrop
)
async def vote_callback(self, interaction: disnake.MessageInteraction):
...
async def on_timeout(self) -> None:
...
Also min and max values are default 1
I feel stupid for not really thinking that would work, thank you!
Haven't tested it tough.
I don't think so...?
I'm not the best with classes, but to my understanding it shouldn't
I mean you could make the Select class in a nice function looks kinda ugly right now.
maybe
the main reason I wanted to merge the two was because I thought if they in the same class, I won't have two classes with only one use case
I think classes like that look way better.
honestly...
I am starting to think that too xD
but thank you for the help either way!
It depends if you got like a good Select create function it can be better if you got a short selection.
But imagine in some cases selection could be really complicated.
ig...
I'm still new to all the newer stuff
so I'm still trying to figure out how to use them all
new to the newer stuff
mhm, sense has been made
Same I just made a ui a week ago dw.
,
xD

Because people smol brain
like us
damb
Our brains may be smaller but they work more efficient.
we reduced the size for more storage for other non important stuff 
,
"Please remember this ..." forgets
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
as soon as i start typing, this happens π
Ryuga is always ot
Sad
only when ash is around
hi guys how to add cooldown to discord command reset in one time every day? for example 00:00 ECT
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
@client.command()
@commands.has_permissions(ban_members = True)
async def ban(interaction: discord.Interaction, member: discord.Member, *, reason: str):
try:
await member.send(f"You have been banned in {interaction.guild} for {reason}, Would you like to appeal? Join this server: ")
await interaction.response.send_message(f"{member.name} has been banned for {reason}")
except:
await interaction.reply(f"The user you are trying to ban has DM's closed", ephemeral = True)
if not member:
await interaction.send("Please specify a username")
await member.ban(reason=reason)``` any ideas?
when i do !ban it doesnt return the message
like please specify a username
how to make my bot auto restart at one time a day? (00:00 ECT)
why huh?
Run a scheduler to do that
!pypi apscheduler
or maybe coz he's using replit
Can someone help me ****
Because you are trying to use member before it is defined.
This will also raise missing required argument first.
TypeError: send() got an unexpected keyword argument 'end' is this error fixable?
await ctx.send(timer, end="\r")
well, you can't do end= in send
All errors are fixable. And the error kind of says it all
I believe \r is the carriage return?
Discord doesn't respect such characters, so just leave that part out entirely
That's correct
ok
and something else
I made a converter which converts seconds to days, hours, minutes and seconds but when i type the command, the bot just spams the message and thats the way it counts. Is there a way to edit that message so the bot doesnt spam ?
I think this can be solved with fetch
!d discord.Message.edit
await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
Also you're probably going to get ratelimited
Something like this might be better: <t:1657908120:R>
unix timestamps best
Does anyone know how I do it so when I run the ban command (or kick, whatever), the user can't ban the bot from the server?
A simple if statement is good enough
I already tried
No user can ban themselves
Can I see what you tried?
yes they can
if they use a bot and the bot doesn't have an if preventing it, they can ban themselves yes
1 sec
1
well here i go try it to show
Idk what you are doing anyway
You can
The what
Well not technically
What about roles hierarchy
You can't ban users that have higher or same top role with you
in fact, he cannot ban himself
recommended places to get started?
Check out the pins of this channel to get you started
Understandable, have a great day
@commands.command()
@commands.has_permissions(ban_members=True)
async def ban_member(self, ctx: Context, member: Member) -> None:
if ctx.bot.user.id == member.id:
return await ctx.guild.leave()
...
``` lmao
Lmao
hello, how can I use discord components (such as Button etc...) in discord.py?
you need to install discord.py 2.0 from git
how can I get the repo?
python -m pip install git+https://github.com/rapptz/discord.py
isn't it unofficial?
no.
you can do python -m pip show discord.py in ur terminal to see which version you have installed
in code you can do discord.__version__ for the same
it's the correct one, thank you
and now, where do I find documentation to finally start to code with components?
check out the example code here https://github.com/Rapptz/discord.py/tree/master/examples
is the d.py version 2.0 documented?
it is, but i dont think the ui part is
stuff related to buttons and menus arent for now
it basically explains why I came asking here
kk
thank you, Ryuga
It is
!d discord.ui.Button for example
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
its under interaction ok, my bad
Where should I add it then?
Well code reads from top to bottom.
Should I add it before the try statement?
Yes.
Ok
but where should I add that?
example
await ctx.send("Message") #where to add the button instance?
you make an instance of discord.ui.View then you add a button to that view and then you send the message with the view, something like this:
view = discord.ui.View()
view.add_item(discord.ui.Button(...))
ctx.send(..., view=view)
what is the diffeence between client and botp
you dont have prefix commands in discord.Client
thanks
so using bot is better?
if you want your bot to have prefix commands, then you should use that. There is no better option it depends on what you want
Yes. commands.Bot is a subclass of discord.Client, which means it can do everything discord.Client can, and more, like prefix commands.
i seee
Keep your usecase in mind though. For interaction bots that don't work with prefix commands, discord.Client will work
btw I found components documentation https://docs.pycord.dev/en/master/
that is the documentation for a fork of discord.py so it will be different
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
these are the docs for discord.py
and docs for components here https://discordpy.readthedocs.io/en/latest/interactions/api.html
I have function which converts seconds into days, hours, minutes and seconds and then i want the bot to countdown that time but I dont want to use while loop
Any ideas?
you have to create a task
but you have to use a while loop
( as I know )
Is there a way to use nested buttons callbacks?
channel = bot.get_channel(int(id))
view = View()
button = Button(label="Open ticket", style=discord.ButtonStyle.green, emoji="ποΈ")
async def button_callback(interaction):
category = await ctx.guild.create_category(f"ticket {ctx.author.name}")
await category.set_permissions(ctx.author, view_channel=True)
await category.set_permissions(get(ctx.guild.roles, id=996392936197599243), view_channel=True)
await category.set_permissions(ctx.guild.get_role(ctx.guild.id), view_channel=False)
channel = await ctx.guild.create_text_channel("chat", category=category, sync_permissions=True)
embed=discord.Embed(title="Ticket ", description="Welcome, this is a private chat with founders.")
embed.add_field(name="You can ask us everything", value="Enjoy!", inline=True)
quit_view = View()
quit_button = Button(label="Close ticket", style=discord.ButtonStyle.red, emoji="ποΈ")
async def button_callback(interaction):
print("program doesnt reach this part of code")
category = interaction.response.message.channel
if "ticket" in category.name.lower():
for ch in category.channels:
try:
await ch.delete()
except AttributeError:
pass
await category.delete()
quit_view.add_item(quit_button)
await channel.send(embed=embed, view=view)
view.add_item(button)
embed=discord.Embed(title="Contact us")
embed.add_field(name="You can privately talk to us", value="Ask anything you need to!", inline=False)
await channel.send(embed=embed, view=view)
await ctx.send(f"Message successfully sent. {channel.mention}")
why do you want nested callbacks?
because one button creates a channel where the bot writes another message in. That new message has a button to delete that channel
then make the callback of the new button delete the message
button1 -> creates -> channel "A" -> bot adds a message that has button2 into channel "A"
button2 -> deletes channel "A"
that's the flow i want to get
basically i just need the second callback to work
like this:
def cllback_button1(...):
...
view = discord.ui.View().add_item(new-button)
interaction.response.send_message(..., view=view)
def callback_new_button(...):
# ur code
and how can I refer to code to specific go to that func?
you just add the button with the new callback
yeah
to the view and send it
but I have to do it inside the first callback
why?
the first callback creates the possibility to run the second one
.
yea but that doesn't mean you have to make the callback there
okay
you can just make two buttons, then in the callback of the first button send the new button when you want
here's the code
i dont know the syntax to do that
I am using
async def button_callback(interaction):
i never specified that the button callback function has to be that one
it does it automatically because it's inside the command
is there a way to do something like that? button = Button(label="button" ecc, callback=myFunc)
def callback_button1(...):
...
view = discord.ui.View().add_item(button2) # you add the new button to the view and send it
interaction.response.send_message(..., view=view)
def callback_new_button(...):
# ur code
button1 = discord.ui.Button(...)
button1.callback = callback_button1
button2 = discord.ui.Button(...)
button2.callback = callback_new_button
like this
π
TypeError: create_text_channel() got an unexpected keyword argument 'sync_permissions' always worked for me. Not working in the new version
That only exists for CategoryChannel.create_text_channel
Oh wait, it seems to have been removed altogether
so how can I sync permission?
If you don't provide any overwrites it will sync automatically
hey guys'
who can fix it?
import discord
import time
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix ='!', help_command=None, case_insensitive=True, intents=intents)
@bot.event
async def on_member_join(member):
channel = member.guild.get_channel("970649770555244584")
embed = discord.Embed(color=0x4a3d9a)
embed.add_field(name="Welcome", value=f"{member.name} has joined {member.guild.name}", inline=False)
embed.set_image(url="https://newgitlab.elaztek.com/NewHorizon-Development/discord-bots/Leha/-/raw/master/res/welcome.gif""")
await channel.send(embed=embed)
bot.run('')
error for cooldown command??
i want sent when cooldown expires
async def claim(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
embed = nextcord.Embed(title="This ticket has been claimed.", color=nextcord.Color.blurple())
embed.add_field(name = "e", value = f"e")
await interaction.response.send_message(f"<@{interaction.user.id}>" , embed=embed)```
How do i change the label name upon interaction (DM ME IF YOU KNOW )
inside an on_message listener how do i detect if the message is sent in dms
you can check if the guild is None
how?
!d discord.Message.guild
The guild that the message belongs to, if applicable.
π₯Ί
Or, check the type.of message.channel
pls explain that one
async def claim(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
embed = nextcord.Embed(title="This ticket has been claimed.", color=nextcord.Color.blurple())
embed.add_field(name = "e", value = f"e")
await interaction.response.send_message(f"<@{interaction.user.id}>" , embed=embed)```
How do i change the label name upon interaction (DM ME IF YOU KNOW )
isinstance(message.channel, DMChannel)
DMChannel? it says thats not a thing
if message.guild is None:
...
if not message.guild:
...
if isinstance(message.channel, DMChannel):
...
many ways
!d discord.DMChannel
class discord.DMChannel```
Represents a Discord direct message channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channelβs hash.
str(x) Returns a string representation of the channel
ok
just use the module object to access the class lol
sry i havent used python in like 3 months...
so like this?
@commands.Cog.listener()
async def on_message(self, ctx:commands.Context, message):
if message.guild is None:
await ctx.send(":thumbsup:")
or no ctx
no context
yes
thx, it works
AttributeError: 'NoneType' object has no attribute 'edit' why i get this error?
await msg2.edit(embed=winning)
as you can see i am trying to edit an embed that has been already edited
π₯
how do i make it so that the bot has a set message made, but then waits for 2 seconds, and while its waiting on discord it shows "botName is typing..." and then sends it after 2 seconds
this is inside commands.Cog.listener btw
can someone help me with this?
Common error. The deleted message was empty
E.g if they deleted this message:
_ _
oh okay thank you
But this is not empty
No. but discord won't let you have that as a field
I have to check if a message sent is in a specific channel, i know how to do this using on_message function and checking if it falls under a specific channel but that seems inefficient.
why is it inefficient?
you can use a decorator for more advanced thing
Is it possible to have an on_message inside a slash command?
something like this:
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**...
so, the on_message would be outside the command and wait for the command to start?
also no
use the wait_for() to wait for a message to be sent
open the link and see the examples
is something wrong? it doesn't work, no errors or anything
this is the whole code (the cog at least) and what is not working is everything after "say something"
yes, i am using the command, the bot responds "say something" and nothing more after i type other things
oh, i think i forgot the @commands.Cog.listener()
let me see
basically, i want it so my command is used to start receiving the messages people type, and if the message is what i want, the bot responds to them
i dont know if on_message is supposed to be inside the command or not, the guy before said that it doesn't need to be outside
on_message in a command????
it worked, thank you!
the examples of wait_for made me think that it should be used inside an on_message event
ive moved to python general and networking so i dont go ot with sarth and ash or sarth or others anymore π
imagine
does anyone know where i can learn how to have my bot display different embeds depending on whether the user reacts with βοΈorβΆοΈ?
now im taking a 70 hour long course for networking :D
and I just wanna get un-sick
ot
i haven't gotten sick in like 3 or 4 years
you have to make the embed in a function outside the class where your command is in, and return the embed, then in the command you use embed=Name_of_your_function(), the same in the buttons
example:
def embed(page):
embed = discord.Embed(title='title',description='description',color=discord.Colour.blue())
return embed
class Buttons(discord.ui.View):
def __init__(self, page:int):
self.page=page
#YOUR BUTTON
self.page+=1
await interaction.response.edit_message(embed=embed(self.page))
class Command(commands.Cog):
#YOUR COMMAND
page= 0
view = Butttons()
await interaction.response.send_message(embed=embed(page), view=view)
i'll try to use this, thank you
thats how a friend told me to do in my code, is there a better way to do this? i would like to know
when the person press the button i make it so the embed func is called again with new arguments
what
doesnt work that way
you are simply stating an example of sending a view within a slash command
like:
page = 0
the command makes the embed in page 0, when i press the button page+=1 and embed=embed(page)
what your like: states and the example states is completely differeny, no offence
different*
phone smh
maybe i explained it poorly then, but how i explained in the like: is it still bad(the command)?
can you explain how to make it better?
I'm on my phone rn soooo, too much work ps typos, I'll either mention later
its ok, thank you!
!pypi reactionmenu
error, but i did it without and it didnt work
async def setup
tysm simple and ez man
fr means alot
uh
new error ommand raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url_as'
code py @commands.command(name = "wanted") @commands.cooldown(1, 10, commands.BucketType.user) async def wanted(self,ctx,Member: discord.Member = None): if Member == None: Member = ctx.author wanted = Image.open("wanted.jpeg") asset = Member.avatar_url_as(size = 128) data = BytesIO(await asset.read()) pfp = Image.open(data) pfp = pfp.resize((241,238)) wanted.paste(pfp, (106,210)) wanted.save("profile.png") await ctx.reply(file= discord.File("profile.png"),mention_author = False)
Dpy 2.0 changed that
Iirc .avatar.url_as(...)
oh
im now getting this Command raised an exception: AttributeError: 'NoneType' object has no attribute 'url_as'
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
!d discord.User.avatar
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
shouldnt it work like this?
im trying to do it for other ppl not just me
You just need to check whether it's None first
can you help me?
Altho you resize later anyway so don't really see the point in that line
Anyone have any idea on how I can install slash commands? I have already tried python3.8 -m pip install -U git+https://github.com/Rapptz/discord.py
async def claim(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
embed = nextcord.Embed(title="This ticket has been claimed.", color=nextcord.Color.blurple())
embed.add_field(name = "e", value = f"e")
await interaction.response.send_message(f"<@{interaction.user.id}>" , embed=embed)```
How do i change the label name upon interaction (DM ME IF YOU KNOW )
Guys i ahve loaded a cog called helpinfo.py and the comand in it is not working what can be the reason?
show code
Ah i did mistake
I made a error handler and it eat up errro
But i still have error can you help
fix what
send the full error
should use json.load instead
Oh
I got this error now
your JSON file is invalid
Hmm
async def claim(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
embed = nextcord.Embed(title="This ticket has been claimed.", color=nextcord.Color.blurple())
embed.add_field(name = "e", value = f"e")
await interaction.response.send_message(f"<@{interaction.user.id}>" , embed=embed)```
How do i change the label name upon interaction (DM ME IF YOU KNOW )
Construct a new view with new buttons and send it
So i want to make a basic command, the work flow :
when we mention a user while running the cmd:
bot sends "ok"
when we dont mention a user while running the cmd:
bot send ("not ok")```
can anyone tell me how to make it ?
like how to make a check in the arguments of the cmd
@bot.command() # Initiating a command
async def cmdname(ctx, member: discord.Member = None): # Defining the arguments, setting member to not None, will cause an error for MissingRequiredAguments
if member is None: # Basic Python, you should know what this does
await ctx.reply("not ok") # replying to the "context"
elif member is not None:
await ctx.reply("ok")
hello guys hope you are good. Can anyone tell where to learn about making discord bots
This is not a Modmail thread.
!resources Do you know the basics of Python? Feel free to look at the official docs if you do, if not check out this
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
yes working in it as data scientist
and its project
https://docs.python.org/3/tutorial/ (official tutorial)
http://python.swaroopch.com/ (useful book)
https://automatetheboringstuff.com/ (for complete beginners to programming)
http://greenteapress.com/wp/think-python-2e/ (another decent book)
See also:
http://www.codeabbey.com/ (exercises for beginners)
https://realpython.com/ (good articles on specific topics)
https://learnxinyminutes.com/docs/python3/ (cheatsheet)
Collection of programming problems to practice solving, learn to program and code, and win certificates
here
Then just look at the documentation for discord.py, you should get into it pretty easily
ok thanks for helping me i will check it out
No problem, good luck π
you have made brother
"you have made brother" 
we cant mention users in the embed title right ?
nop
cool
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UndefinedTableError: relation "suggestionchannel" does not exist
does anyone know how to fix it?
not really sure what he was trying to tell me
cause it would check all the messages?
quick question, how often does tasks.loop() runs when no time kwarg is provided
yes, but that's definitely not a problem
no arguments were passed?
infinite times/sec
no
then?
hi guys
i have a question
how can i do to my bot that it will send every 120 minutes a message?
let me measure it, one moment
cool sure
tasks.loop(minutes=120)
every 1/37644 seconds approximately
async def test(ctx):
await ctx.send("hi")
tasks.loop(minutes=120) ```
would this work?
from discord.ext import tasks
oh ok
no
how would i do it?
from discord.ext import tasks
@tasks.loop(seconds=5)
async def my_loop():
print('Hello World')
my_loop.start()```
oh okay thanks
:D
np
ayo what π
this is 1 second and it prints that much
β οΈ
@odd mango ```@tasks.loop(minutes=120)
async def bump(ctx):
channel = bot.get_channel(992511703155740712)
await channel.send("@fair kite bump")
@bot.event
async def on_ready():
bump.start()
```this will work right?
this works but i'll suggest to add a await bot.wait_until_ready() in the first line of the bump coro
^^^
it waits for the bot to fill its cache before executing the next line
okay
also bump is not the command here just so you know
its the event name to be looped
savvy pro
it will start as soon as your bot starts
what
ok bro
ctx is not available there
yeah you dont need a trigger to start it
oh sorry for the ping
okay
more like no Context will be passed there since its a task, Context is meant for commands.
yes
ok, i removed it
also why are you starting it in on ready β οΈ
i removed it
AttributeError: 'NoneType' object has no attribute 'send'
what
did you add the bot.wait_until_ready()?
@tasks.loop(minutes=1)
async def bump():
channel = bot.get_channel(992511703155740712)
await channel.send("@fair kite bump")
bump.start()```
oh
wait where do i add that?
at bump.start?
bot wont get the cached channel until its ready
1st line of the bump coro
ok
@tasks.loop(minutes=120)
async def bump():
await bot.wait_until_ready()
channel = bot.get_channel(992511703155740712)
await channel.send("@fair kite bump")
bump.start()```
an async function
coroutine
okay
async def foo(): ...
``` `foo` is a coro/coroutine here
thanks
make a command handler 
Ye good idea i was thinking to do for all my comamnds
maybe make server analytics & statistics feature
Whats this?
server info
serverinfo and stats command.
member count creation date and all
for some stats parts you may need a db, its optional tho
i bet asher would use dict
like which is the most active channel, messages/day, most popular topic to talk, etc
economy bots are boring. just rip-offs of dank memer.
if you make it nice enough π
Rpg bot?
raise RuntimeError("PyNaCl library needed in order to use voice")
RuntimeError: PyNaCl library needed in order to use voice
The above exception was the direct cause of the following exception:
how install discord.py 2.0 [voice]
My brain would blast
its pain but if you want to then okay
please
pip install -U git+https://github.com/Rapptz/discord.py
Donwload PyNaCl?
you need to install pynacl...
!pip pynacl
$ git clone https://github.com/Rapptz/discord.py
$ cd discord.py
$ python3 -m pip install -U .[voice]
dpy 2.0 has it built in no?
nope
oof
if you're on a linux based os, you would have to install libffi-dev
sarth how do i get db latency
just calculate the time taken to execute an query
hm ok
ty
I not helped tho
Oh alright, thank you sm!!
Also if may I ask is there any list of errors that a command can give and i can put them
Like in the @function.error
import PyNaCl
ModuleNotFoundError: No module named 'PyNaCl'
pip install pynacl
after that pip install -U .[voice]
not work
.
it has for the voice version it installs as dependency
yes but not with the github link
you would have to clone and install to install the master voice support
cd discord.py not found
is making a bump reminder hard?
nah
intermediate
oh okay
u just need bit of logic and problem solving ability with python
okay
did you run all the commands?
@tasks.loop(hours=2)
async def remind():
cnl = bot.get_channel(...)
await cnl.send("Bump Time!")
π
what if someone doesnt ping at exact 2hr time
... how many people are stuck in the questions why is my discord bot not running not responding π
Then.... best of luck
yeah, one problem. if the user bumps a little later the time wont be correct
sarth just gonna make another 1000 line SQL for them then
yea
message_content intent!
i already did something like that
there's no db needed for that tho lol
cache 
just being sarcastic π
at worst just use a json
cries in mongodb
Just use text files dude
today's ot channel
Or .cache files
json-derulo
Indeed
made my morning brighter
use sqlite3 in memory
@rugged tulip
Might as well just use cache
@rugged tulip
π₯ just dont make bots
ikr just study chemistry
ong
organic i am gonna die π π
@rugged tulip
y are u pinging
I need help
so basically, i created multiple files that has commands without prefix, embed and stuff separetely. idk why but only one of my file would work
I have a bot that is in three servers when i wrote this code
@client.command(name='serverids', aliases=['si'])
async def serverids(ctx):
for guild in client.guilds:
await ctx.send(guild.id)```
I got those three server's ids all of them
but just like this i wanted to add these ids into database(mysql) with a command so i wrote this
```py
@client.command()
async def insertTables(ctx):
for guildid in client.guilds:
cur.execute(f"INSERT INTO Servers(serverid,sub,subdate) VALUES({guildid.id},0,CURDATE());")
conn.commit()```
but i got one of the server's id three times and saved in three rows in data base instead of getting three server's id what is the problem?
async def on_message(ctx):
if ctx.content() == "/bump":
asyncio.sleep(1)
await("<@&984101784719069184> you can bump again")
await bot.process_commands()
else:
await bot.process_commands()
``` hi guys why isnt this working? nothing in the console
nvm
error is: File "e:\Users\elias\PycharmProjects\Python irgendwas\venv\discord bot\bot.py", line 717, in on_message
if ctx.content() == "/bump":
TypeError: 'str' object is not callable
why using ()?
what where?
also just use the command decorator
oh
where?
async def on_message(ctx):
if ctx.content == "/bump":
asyncio.sleep(1)
print(asyncio.sleep)
await("<@&984101784719069184> you can bump again")
await bot.process_commands()
else:
await bot.process_commands()```so like this?
use @bot.command() decorator instead of event
oh okay
I see no issue in your code
Yeah I dont why it's not working properly
I mean it should loop through client.guilds and add them into db one by one
@honest shoal ```@bot.command()
async def bumpreminder(ctx):
if ctx.content == "/bump":
asyncio.sleep(1)
print(asyncio.sleep)
await("<@&984101784719069184> you can bump again")

is it just me who's too lazy to make a time converter