#discord-bots
1 messages · Page 491 of 1
while True is blocking
how could I go around that then
beause I would like to be able to control from python console
why tho lol
ultimate goal is to make an UI
but im far away from that
with my skills
im trying to learn
What?
ui?
GUI
yes i know
I got a weird problem in vscode. It just keeps saying this after this line...
I'm indenting properly yet it shows error.
Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message
https://github.com/AA1999/Disthon
...
I know i did something wrong but i am not getting what i did wrong and how do i fix it. I am trying to make a pagination menu controlled by an emoji with a list.
Some one please help me. It is related to python so i asked here
Code:
https://cdn.discordapp.com/attachments/381965515721146390/890446763641679902/unknown.png
@proud sierra please use range(lower_bound, upper_bound_excluded) instead of that lis
lower_bound is included and defaults to zero if only one arg is provided
seriously, that's a hate crime. anyways what's the error? it doesn't look like you've done import asyncio
Just reindent everything lol
i closed and reopened the file
it's gone
weird vscode
hm
So I've noticed that @unkempt canyon 's !d documentation refers to the master branch, whereas the latest update I get through pip is the stable branch - and there are breaking differences. Which should I be using? I thought development on discordpy had halted?
it is?
!d discord.ext.commands.Bot
hm
Yeah check the link, it refers to /en/master
Ah so the master branch is v2
yes
Was that never officially released, since it's not a part of pip?
part of pip? its not released on pypi
uh yeah pypi i meant
is it like a trusted and widely used fork? how come the documentation refers to it?
what fork?
its discord.py 2.9
0*
its on the master branch of the github
i dont get what you mean
If the latest pypi release is 1.7.x, and development has halted, then surely 2 is never going to be released? Why is it the default for the bot's documentation? I just find that strange, but there may not be any definite answer
Like, does anyone use 2?
yes?
the bot's docs got changed just a few days ago
and i dont see an issue with it
you can still install 2.0
pip install git+<github url>
i dont see the issue here
Maybe best to wait for someone who understands what I mean then.
i mean, yes 2.0 is probably never going to be released to pypi
Hello, I'm trying to make a temporary text chat when someone joins a specific vc. How do I make it so that the text chat get's deleted when there are no users in the vc?
async def on_voice_state_update(self, member, before, after):
if member.bot:
return
if after.channel is not None:
if after.channel.name == "☕・Quarter-05":
await create_text_channel(after.channel.guild,'☕・Quarter-05 chat'.lower(), category_name='⎯⎯⎯⎯⎯ 🔒・Private ⎯⎯⎯⎯⎯⎯' )
but that doesn't mean you cant install it
len(channel.members)
I was under the impression development had halted (https://gist.github.com/Rapptz/4a2f62751b9600a31a0d3c78100287f1).
how does it know the text chat it created
yes it did
No time for explain right now sry.
You can use db for store channels ids.
how can i get a list of unloaded cogs ?
apparently doin [cog for cog in bot.cogs]
return a list of loaded ones i need a list of unloaded ones
ping me with answer
Well I don't think u can tbh... U can instead try reloading the Cogs and an error in raised if u try to reload the unloaded cogs
you can subclass Bot and keep track of unloaded cogs yourself
for example have a list, append to it when unload_extension is called, remove from it when load_extension is called
if you have a list of all the extensions there is a way
all_cogs = ...
unloaded_cogs = set(bot.cogs.values()) | set(all_cogs)```
Hey Something's wrong here, when I send {prefix}youtube the bot isn't responding at all
async def youtube(ctx, *, search):
await ctx.message.delete()
query_string = parse.urlencode({'search_query': search})
html_content = request.urlopen('http://www.youtube.com/results?' + query_string)
search_results = re.findall('href=\"\\/watch\\?v=(.{11})', html_content.read().decode())
await ctx.send('https://www.youtube.com/watch?v=' + search_results[0])```
still new
even just looking things up on youtube is against TOS so you'll not receive help here
Lol sry
How do I convert message.created_at to it's epoch version (I think that's why my issue lies) because this py plain = f"Sent <t:{int(message.created_at)}:R> by {message.author} in {message.channel.mention}\n\n>>>{message.content}\n\n[Jump to message]({message.jump_url})"keeps sayingpy TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime'and my logs file is sayingpy ERROR:cogs.error_handler:TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime' (In quote) Traceback: File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "/home/modmail/cogs/general.py", line 190, in quote plain = f"Sent <t:{int(message.created_at)}:R> by {message.author} in {message.channel.mention}\n\n>>>{message.content}\n\n[Jump to message]({message.jump_url})"
its message.created_at.timestamp()
ahhh
!d datetime.datetime.timestamp
datetime.timestamp()```
Return POSIX timestamp corresponding to the [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") instance. The return value is a [`float`](https://docs.python.org/3.10/library/functions.html#float "float") similar to that returned by [`time.time()`](https://docs.python.org/3.10/library/time.html#time.time "time.time").
Naive [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") instances are assumed to represent local time and this method relies on the platform C `mktime()` function to perform the conversion. Since [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") supports wider range of values than `mktime()` on many platforms, this method may raise [`OverflowError`](https://docs.python.org/3.10/library/exceptions.html#OverflowError "OverflowError") for times far in the past or far in the future.
For aware [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") instances, the return value is computed as:
```py
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
``` New in version 3.3.
Changed in version 3.6: The [`timestamp()`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime.timestamp "datetime.datetime.timestamp") method uses the [`fold`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime.fold "datetime.datetime.fold") attribute to disambiguate the times during a repeated interval.
thanks blanket
guys, how can i know the MissingPermissions is for the bot or for the ctx.author?
okay and one other thing, why does py <t:{message.created_at.timestamp()}:R>render as <t:1631821395.943:R>in the bots msg and not as a timestamp
.
ok
what error is the bot giving? can you copy paste it here
MissingPermissions is a failed has permissions check, BotMissingPermissions is the bot doesn't have permissions to do the action
<3
Ignoring exception in command kick:
Traceback (most recent call last):
File "C:\Users\moon\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\moon\OneDrive\Coding\Python\dis-bot\cogs\commands\kick.py", line 15, in kick
await user.kick(reason=reason)
File "C:\Users\moon\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\member.py", line 568, in kick
await self.guild.kick(self, reason=reason)
File "C:\Users\moon\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\guild.py", line 1997, in kick
await self._state.http.kick(user.id, self.id, reason=reason)
File "C:\Users\moon\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\moon\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\moon\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\moon\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions```
this is the full traceback
!traceback
this is the bot missing permissions
well hopefully sebkuip's answer helped
how did you know?
its
Missing Permissions
because it's a http 403 and discord error 50013
which is bot missing permissions
bruh
and how to except it
?
discord.Forbidden
try:
# stuff you don't have permission for
except discord.Forbidden:
# you don't have permission
i wanna missing perms
why does py <t:{message.created_at.timestamp()}:R>render as <t:1631821395.943:R>in the bots msg and not as a timestamp
idk why
?rtfm
make the timestamp an int
<t:{int(message.created_at.timestamp())}:R>
yeah it's not liking thatpy TypeError: 'datetime.datetime' object is not callable py plain = f"Sent <t:{int(message.created_at().timestamp())}:R> by {message.author} in {message.channel.mention}\n\n>>>{message.content}\n\n[Jump to message]({message.jump_url})"
this is on_message event right
ah I still have some ( ) in mine, guess i'll remove em
nah it's a quote command
yeah some extra after timestamp
okay they gone and it works
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
@client.command()
@commands.has_permissions(manage_messages = True)
async def remove(ctx, *content):
with open('links.json', 'r') as f:
links = json.load(f)
links[str(ctx.guild.id)] - content
with open('links.json', 'w') as f:
json.dump(links, f, indent=4)
i am very new to python, so i have little to no knowledge over python so im sorry for asking help on such a simple thing
i want to remove the content provided from the .json file
but i do not know how
open('links.json', 'w').close()
does discord bot run multiple funtctions at once or 1per
1 at the time is concurrency?
but while 1 function is executing other functions can execute
i worded it badly, mb
Does d.py support bot proxies so one bot can log into and act as another bot? I was reading some slask and Reddit posts that said that it had been possible but that it was no longer possible due to d.pys pocie system not being compatible with aiohttp and that it requires Https connections or something
Ok I want to format my button like this here is the code: py await ctx.channel.send(embed=report,components=[Button(style=ButtonStyle.red, label="No", custom_id="n"), Button(style=ButtonStyle.green, label="Yes", custom_id="y")])
the output of the code is this
yes but although I want the format of the buttons to be like it but its for a completely different purpose
Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message
https://github.com/AA1999/Disthon
Why isn't this working?
for roles in ctx.guild.roles:
rola = []
rola.append(roles)
await ctx.send(", ".join(rola))
roles is not defined
you can just do py await ctx.send(", ".join(r.name for r in ctx.guild.roles))
yep
thanks I'll try it.
though it is, at least for me, better if you make an embed, and send the role mentions
and also there is allowed_mentions
yes, i was planning to do that thanks
also it pinged @everyone 😔
lol rip
ctx.guild.roles[1:]
this is to remove the @everyone.
hm ok
because @everyone is the first role right?
https://hastebin.com/rufulopuxo.py
The cog works fine, but the commands.dm_only() isnt working
oops
owo
!e
roles = ['a', 'b', 'c']
print(roles[1:])
@spring flax :white_check_mark: Your eval job has completed with return code 0.
['b', 'c']
thanks!!
Basically the question is, How do I do an dm only cmd in an class. And how do I make It visible at the regular standard help cmd
I mean cog*
I'd like to help.
What languages are you good at?
typethon
Typescript and Python ym?
Typethon
guild = self.bot.get_guild(int(key))
ValueError: invalid literal for int() with base 10: 'member_count'```
what does this mean?
Key is probably not base 10
!e int('member_count')
@cloud dawn :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ValueError: invalid literal for int() with base 10: 'member_count'
Most likely this is a dict so you'd need to get the value
That are a lot of members
Your naming is bad
ye ik and thats a channel id not members
how so?
Your answer #discord-bots message
its a channel id

Can you show your key variable @waxen granite
async def statscounter(self):
for key in self.serverstats.keys():
guild = self.bot.get_guild(int(key))
print(key)
try:
server_stats = self.serverstats[str(guild.id)]
except KeyError:
server_stats = {}
category = discord.utils.get(guild.categories, name="STATS")
botcount = 0
membercount = 0
members = guild.members
textchannelscount = len(guild.text_channels)
voicechannelscount = len(guild.voice_channels)
for member in members:
if member.bot == True:
botcount += 1
else:
membercount += 1
users_text = f"Users: {membercount}"
bots_text = f"Bots: {botcount}"
channels_text = f"Text Channels: {textchannelscount}"
channels_voice = f"Voice Channels: {voicechannelscount}"
tier = f"Premium Tier: Level {guild.premium_tier}"
uc = guild.get_channel(server_stats['member_count'])
bc = guild.get_channel(server_stats['bot_count'])
tc = guild.get_channel(server_stats['text_count'])
vc = guild.get_channel(server_stats['voice_count'])
pt = guild.get_channel(server_stats['tier'])```
it prints the key
when i am running it on my pc
but on host it gives that error :3
serverstats is probably the guild Id
ye
it's wrong then, you are iterating over the inner dict
hm
How can I install all modules in 1 time?
uh?
could you elaborate on your question?
uhh
sec
Hello help pls...
I found out how to change a permision to False or True in a Role but how to set a permission to default?
.dpy
like this
import discord
How do I install that and all other? Whats the command for that to install in 1 time
I know
i have done all necessary imports, and there is no errors, the problem is my logic isn't working , i wanted to created page embed and if i react with next emoji, then the embed will be edited and will display content from the list in 10 parts
Halp pls
pip install -U discord.py
ty
you cannot i g, you need to remove the role and again add it ig
or maybe actually use PyCord with pip install -U py-cord
it's a fork so everything looks the same as in discord.py for now
hm
I remember it being None
guys, if i host my bot on my computer, does it return back my c disk space after stopping it?
your python files will take the storage space
and that's just sitting there
it doesn't care if it's running or not
yes, but when its running
that's not how storage works
it slowly drains my c drives disk space
so im asking if it returns the disk space after stopping it
That is if it writes new files, or updates files.
oh, for me just running it takes disk space even without editing files
Other than that, shit happens using your computer's RAM.
RAM is not where files are saved.
i only have 4gb ram
I can defo use TS knowledge in my team
Interested?
Typethon
hey guys, how many ram does a bot take to run itself?
for me, the bot is light
i only have 4gb ram so i wanna have the exact amount to adjust my virtual ram amount to run it on my computer, it is not really convenience to just copy pasting code into repl.it because its really annoying
thanks!
4gb ram is def overkill
for at least a light bot, depends on the member cache size I'd say
depending on your size of bot, max like a few gigabyte
ah
i have 6.5mb virtual ram
along with vscode, firefox and discord
those apps only will take 4gb+
can we add 2 or more perms as True in .has_guild_permissions?
I believe you can. but tias
disnake >>>
hello i have a problem with a levelling bot
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed: Embed size exceeds maximum size of 6000
i know but look the code
@commands.command()
async def rank(self, ctx):
if ctx.channel.id == bot_channel:
stats = leveling.find_one({"id" : ctx.author.id})
if stats is None:
embed = discord.Embed(description="Tu n'as pas encore de level !")
await ctx.channel.send(embed=embed)
else:
XP = stats["XP"]
lvl = 0
rank = 0
while True:
if XP < ((50*(lvl**2))+(50*lvl)):
break
lvl += 1
XP -= ((50**((lvl-1)**2))+(50*(lvl-1)))
boxes = int((XP/(200*((1/2) * lvl)))*20)
rankings = leveling.find().sort("XP",-1)
for x in rankings:
rank += 1
if stats["id"] == x["id"]:
break
embed = discord.Embed(title="{} level stats".format(ctx.author.name))
embed.add_field(name="pseudo", value=ctx.author.mention, inline=True)
embed.add_field(name="XP", value=f"{XP}/{int(200*((1/2)*lvl))}", inline=True)
embed.add_field(name="Rank", value=f"{rank}/{ctx.guild.member_count}", inline=True)
embed.add_field(name="Progression", value=boxes * ":blue_square:" + (20-boxes) * ":white_large_square:", inline=True)
embed.set_thumbnail(url=ctx.author.avatar_url)
await ctx.channel.send(embed=embed)
so many emoji's ohno
Where ?
this is a bar progress
how can I do that if I choose 10 winners, to not pick the same user?
Make a list, add the user to list if that user is not in the list
That's a general idea, do however you like
ok thanks
would this work
tias
@tasks.loop(minutes= 30)
async def statscounter(self):
for key in self.serverstats.keys():
guild = key
try:
server_stats = self.serverstats[str(guild)]
except KeyError:
server_stats = {}
category = discord.utils.get(guild.categories, name="STATS")
botcount = 0```
in `category = discord.utils.get(guild.categories, name="STATS")` says str obj has no attribute categories. how should i get the categories then ?
Print guild please
!d random.choices
random.choices(population, weights=None, *, cum_weights=None, k=1)```
Return a *k* sized list of elements chosen from the *population* with replacement. If the *population* is empty, raises [`IndexError`](https://docs.python.org/3.10/library/exceptions.html#IndexError "IndexError").
If a *weights* sequence is specified, selections are made according to the relative weights. Alternatively, if a *cum\_weights* sequence is given, the selections are made according to the cumulative weights (perhaps computed using [`itertools.accumulate()`](https://docs.python.org/3.10/library/itertools.html#itertools.accumulate "itertools.accumulate")). For example, the relative weights `[10, 5, 30, 5]` are equivalent to the cumulative weights `[10, 15, 45, 50]`. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.
key is the guild.id
Ah, I was finding that
Well please print guild and show
isnt key = guild ?
?
i just noticed the cum_weights
cum has been the abbreviation of cumulative for years and people still joke about it? really?
I never read anything
i mean guild is key = guild id
bc cum is cum
And it's treating it as a string... U will have to do get_guild(int(guild)) then go the utils.get
ik how to use, idk how to make that thing
seb just told you
yes, I know the random.choice thing
random.choices*
for key in self.serverstats.keys():
guild = self.bot.get_guild(int(key))
try:
server_stats = self.serverstats[str(guild)]
print(server_stats)
except KeyError:
server_stats = {}
category = discord.utils.get(guild.categories, name="STATS")```like this?
👍
async def statscounter(self):
for key in self.serverstats.keys():
guild = self.bot.get_guild(int(key))
try:
server_stats = self.serverstats[str(guild)]
print(server_stats)
except KeyError:
server_stats = {}
category = discord.utils.get(guild.categories, name="STATS")
uc = guild.get_channel(server_stats['member_count'])```
gives keyerror 'member_count' but i have it here
bc your try/except got a KeyError exception and made an empty dict for server_stats
but it printed server_stats
maybe worked for the first few ones but what about the rest
what exactly is self.serverstats defined as
with open("./botFiles/stats.json", "r") as f: self.serverstats = json.load(f)
and what do u have in that stats json
how i make a embed create command?
why wont this check work.
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.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
you also can do dict.get(key, default) instead of handling KeyError
can anyone hel[
how i make a Embed creator command?
i just showed u
does anyone works on the future of discord.py or is it "dead" ?
so this do this?
yes
they is no official person that will work on it but there are forks
it's just no longer developed , promising forks like disnake and pycord exist
hey, how do i make the emoji stealing command?
import datetime
from discord.ext import commands
import aiohttp
import os
import random
class ImageSearch2(commands.Cog):
def __init__(self,client):
self.client = client
self.client.ses=aiohttp.ClientSession()
@commands.command()
async def image(self,ctx,*,search):
search = search.replace(' ','')
url =f'https://api.unspalsh.com/photos/random/?query={search}&orietation=squarish&content_filter=low&client_id={unsplash}'
async with client.ses.get{url} as r:
if r.status in range(200,299):
data = await r.json
mbed = discord.Embed(
title = 'Here is your image'
).set_image(url=url)
else:
await ctx.send(f'Error when making reuest.{r.status}')
def setup(client):
client.add_cog(Chatbot(client))``` I am receiving syntax error pls help
@potent jetty Its datetime.datetime
!d discord.Guild.create_custom_emoji
await create_custom_emoji(*, name, image, roles=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a custom [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji") for the guild.
There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.
You must have the [`manage_emojis`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_emojis "discord.Permissions.manage_emojis") permission to do this.
do datetime.datetime.utcnow()
try using the var u made?
because member.joined_at has a timezone (utc)
yes
!epy import datetime print(datetime.datetime.now())
my bad
It might be () not{}
Yes
Idk what lib r u using
@slate swan
aiohttp I guess
No prolly
it still gives
that's not valid in any case
ClientSession as ses
and why i have to use "url" as i have defined url above
Smthng like this
Why {url} tho?
🧐
I forgot how but you can google "How to update to nodejs 16 on replit"
my vsc gets an error too
Node js for what
@reef shell
ah yes the classic, nodejs help in a python server
Same q
and that is?
lol
hey have someone here a mute command src?
are you using 2.0?
Just search in github for a mod. Bot
try x - joindate?
okay
discord.utils.utcnow()```
A helper function to return an aware UTC datetime representing the current time.
This should be preferred to [`datetime.datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "(in Python v3.9)") since it is an aware datetime, compared to the naive datetime in the standard library.
New in version 2.0.
@potent jetty also its .url lol
yep use that
still getting that error
does anyone know how to fix this
nope
api could be fucked
u sure?
aaaaaaaaaaaaaaaaaaaaaa
also why r u using pass context?
same error ig?
you're not supposed to use the json endpoints
yes
use the actual api
relax
Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message
https://github.com/AA1999/Disthon
How many times will you send this
ermmmm
oh sorry i didnt know what should i use then?
the actual api
i may or may not have forgotten what api i use
👍
Hi anyone know how to use the library discord_components?
im trying to fix my code but i dont know where is the bug
read their docs
.
Wolfmoon, don’t worry about asking if you can ask - just send the code you think could be relevant and explain/post the error
The bot send the board but when im going to click the button i want , dont replace the style of button to the mark
Psd: I use the library discord_components
Code => https://paste.pythondiscord.com/uxedicozoz.py
I got permission
Not like I'm tagging anyone specific my guy
i didn't say it either
Actually all the admins agreed to let open source projects be advertised
Thanks homie
anyonehave any idea where is the bug?
nvm
Who can help me?
@waxen granite don't need help anymore?
You need to pip install discord.py[voice]
gotcha
I already installed this but it doesn't work
why did this error occur TypeError: event() missing 1 required positional argument: 'coro' the error starts from this code: py @client.event() async def on_button_click(ctx, *,interaction): sent=discord.Embed(color=0x51ed87) sent.add_field(name='Action Confirmed', value='Report successfully sent', inline=True) if interaction.component.label.startswith("Send"): await ctx.interaction.message.edit(embed=sent) also I have three client events and i am
trying to edit an embed when a button is pressed.
client.event not client.event()
Why would we contribute to this if not you but subkuip is basically making the wrapper..?
??
# JOIN =================================================================================================================
@client.command()
async def join(ctx):
channel = ctx.author.voice.channel
await channel.connect()
# LEAVE ================================================================================================================
@client.command()
async def leave(ctx):
await ctx.voice_client.disconnect()
99% of bots are hardcoded to ignore any message types flagged as a bot sender so sadly no. You could, however, do it with a self-bot but that would break discord TOS and would result in an account ban.
The bot isnt joining 👀 maybe someone can help?
ohk
did you use the Qau link
wu?
I'm making all the models what do you mean?
Yeah he's working with the API but so do I am learning and implementing the api

Your last commit was 15 days ago
let me explain go to
okay
Because I'm working on multiple stuff rn
And all are connected to each other
Haven't commited them
I only marked bot 💀
How do I set the authors pfp in the author?
embed.set_author(name=message.author.display_name + " " + "(" + str(message.author) + ")")
then select bot
ok
and applications.commands
He's definietly doing me a lot of favors, but I can screenshot my stuff and send it to you
then copy your link
what does it say
something like author.display.url or whatever.
That won't be necessary, a readme would also be nice on how to get setup. I will watch it for awhile.
but it isnt working
message.author.avatar_url
Hopefully you'll become a contributor too eventually
avatar.url for 2.0
do
Tell you what, if there could be a small readme on how to get setup i will def debug it myself.
...
Bet
Project tab is also pretty useful so everyone can see what you are working on rn -> https://github.com/AA1999/Disthon/projects
It’s not working
What would I do if it’s sent from a a private channel?
its still message.author.avatar_url
embed.set_author(name=message.author.display_name + " " + "(" + str(message.author) + ")", url=message.author.avatar_url) is this right?
are you v2 discord.py
icon_url = message.author.avatar_url
Ohh
Traceback (most recent call last):
File "C:\Users\juu\OneDrive\bot\venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:/Users/juu/OneDrive/bot/music.py", line 58, in join
await channel.connect()
File "C:\Users\juu\OneDrive\bot\venv\lib\site-packages\discord\abc.py", line 1277, in connect
voice = cls(client, self)
File "C:\Users\juu\OneDrive\bot\venv\lib\site-packages\discord\voice_client.py", line 199, in __init__
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:
Traceback (most recent call last):
File "C:\Users\juu\OneDrive\bot\venv\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\juu\OneDrive\bot\venv\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\juu\OneDrive\bot\venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: PyNaCl library needed in order to use voice
# JOIN =================================================================================================================
@client.command()
async def join(ctx):
channel = ctx.author.voice.channel
await channel.connect()
# LEAVE ================================================================================================================
@client.command()
async def leave(ctx):
await ctx.voice_client.disconnect()
@slate swan RuntimeError: PyNaCl library needed in order to use voice
This code is more organized than my life.
:')
Union[User, Member]: Returns the author associated with this context’s command. Shorthand for Message.author
Give it a week before it becomes a disorganized soup just like the rest of us
Indeed.
so?
About the only bit of organization my code has
hmmm
ctx.author returns a discord.Member object, which doesn't have voice.channel.
!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.
When coding a program you need to atleast recode it 2 more times before it is organized and readable.
lol
more
It does
!d discord.Member.voice
property voice: Optional[discord.member.VoiceState]```
Returns the member’s current voice state.
and voicestate has a channel property
It has voice, not voice.channel.
!d discord.VoiceState.channel
The voice channel that the user is currently connected to. None if the user is not currently in a voice channel.
Here u go
Ah, I'm pretty un-experienced with the voice part. My bad.
voice is pretty doable
Doable yes. Worth it? Probably not.

are you guys talking about the raw things or the stuff that dpy gives
At best you can probably create some sort of bot that joins a voice chat and auto-mutes anybody who mic spams for more than x seconds
Is it possible to see put videos in embeds?
because handling voice is a pain in the ass
Yes
like instead of saying "watching"
!d discord.Embed.video is a thing but no idea if one can send it
property video: _EmbedVideoProxy```
Returns an `EmbedProxy` denoting the video contents.
Possible attributes include:
• `url` for the video URL.
• `height` for the video height.
• `width` for the video width...
It's readable only ig
They cannot have a custom status like a normal user , can use Discord presences like playing watching listening
hm
my bot won't break , since I ain't adding anything new to it
Meanwhile rewriting it in hikari
I created a reddit thing to grab my reddit notifications and display on discord and atm I am still testing it to find all the bugs
and there's this one bug that pops up and I cant seem to figure it out
Using some api library?
the ASYNCPRAW thing
why cant I delete a message
await self.bot.get_channel(890646800019640380).fetch_message(890646834152894485).delete()
AttributeError: 'coroutine' object has no attribute 'delete'
oh
thanks panda hehe
that worked?
um no
i deleted it since i tought it was bogus lol
you can only do that method in an if statement
msg = await self.bot.get_channel(890646800019640380).fetch_message(890646834152894485)
msg.delete()
fetch_message returns a coroutine object
you called delete on it before it could be awaited
oh
await (await self.bot.get_channel(890646800019640380).fetch_message(890646834152894485)).delete()
is that gonna work
why do you have to be complicated
yes
but as gnome said, why
channel = await self.bot.get_channe(890646800019640380)
msg = await channel.fetch_message(890646834152894485)
msg.delete(delay=86400)
because if u put everything on one line it makes it do it faster
what
if only this were true...
by what? half a nanosecond?
1 line bots are going to the moon
i guess im wrong sorry
if you want it to be speed use a compiled language.
Look, if you can do it in 1 line, that's great! fantastic! But there's no shame in doing it in 3 or 4 lines
I like programming because you can do something several different ways
often 1 line can be pretty unreadable so i'd recommend doing it in 2/3 lines even if you can do it in 1
Plus, multi-lines have the benefit of allowing you to use other features.
Like, now that we have the channel variable. we can now do shit like get all the messages in that channel. change its name.
fuck around with it or something.
or now that we have the msg variable. Coz we know we're gonna delete it anyway. Fuck about a bit 😉
msg.edit("Haha nobody gonna see this shit.") followed by a msg.delete(delay=1) xD
msg.edit(content="Haha nobody gonna see this shit.", delete_after=1)
also @leaden jasper where you getting the channel/message ids from?
lol
fuck. u can do that?!
Yes
await (await self.bot.get_channel(self.channel).fetch_message(data['msg'])).delete()
Almost on every .send()/ .edit()
forgot the content= in edit
Very true
It's a task loop that runs every hour
updates a graph by deleting the old message and sending a new message in a channel
Seeing you making a wrapper up for the task?
So you need a specific message to delete? just set the bot to delete it without needing a loop.
i am working with a few others on making a wrapper from scratch yes
no i was just explaining to panda what its for
and well we already have a good connection to discord
just we've got a lot ahead still
anyone know how to use mongoDB?
what's your latency?
I def recommend adding activities to the wrapper since that is going to be pretty big.
The people over at #databases do
how different is it from mine!!
ty
Good luck. They get wild over there.
They actually take their shit seriously
I went in there for like 10 minutes and got yelled at immediately.
it can already receive all events just needs all the code to be able to send. Also needs all the models for the various things in discord
Going strong. no errors yet!
for the user it will look a lot like dpy probably, but underlying there will be some major changes. Main thing @river walrus wanted to change was the cache and how it worked
that makes me cry xd
Likely thus why i said that it is a big task, tough i don't see why you wouldn't fork dpy and adding all the new features and just update it.
same, i hate NoSQL atm
ask arshia, they wanted to go from scratch
I use aiosqlite3 for my db
it's also kinda what interested me, so i understood it from the core up
also this reminds me that I should update my code lol
Parts of my code use CSV as its database.. another part uses json..
and the rest uses a db
import asyncio
Not that much of scratch i see lol
afaik they are not as fast as sql, and they are mostly used to manage static data
also, its a pain filtering it
yes. static.
very muchso. yep yep yep.
then why
I have a question
sql is just better in every way when using python.
he says as the part that changes frequently is the statistics using csv
?
I get when using java you'd use mongo
how many people are in ur group doing this project?
we have a few people that have direct repo access as a contributor like me. And quite a lot of people who are wanting to maybe help here and there by making PRs
lol what you should just refactor everything and switch to sql
I should eventually.
good
eventually
do u guys have an official server for updates and stuff?
I did consider it but there is no setup info in the readme so i need to figure out how to run the whole thing.
dude it’s still in development and you already want to run it
clone the repo
yes we have a discord server
cool is it open to the public or private?
right now it's not on PyPi but once it's sort of stable/usable it will just go to PyPi where you can pip install it
right now you need to use the setup.py and python -m build to install it locally
it's public
oh nice nice can you do me a favor and mail me the thing in dms?
im trying to think of a more discrete synonym for send
To the thesaurus!
Why would you do this? ```py
raise TypeError("The callback is not a valid coroutine function. Did you forget to add async before def?")
raise TypeError(
"The callback is not a valid coroutine function. Did you forget to add async before def?")
Multiple reasons:
- Dpy already has terrible quality forks which are giving the fork process a bad name
- Dpy's code is a mess (I mean the quality is frankly not that great in some areas)
- Since Dpy's cache is unstable, re-writing a cache means changing a lot of code, which makes it easier just to build stuff from scratch
so all event functions should be a coro, so it's just checking if it's a coro before invoking it
No that you changed it to 2 lines instead of one
oh i just ran an auto formatter on it
and i guess it saw that the line is too long
done it a few times here and there
I mean yes quality does suffer if the owner of the git isn't checking the work and there are 100+ contributors.
okay try reading the source code then
am concern.
it's getting slower..
i tried to look in dpy's source to see how the gateway and login is done
it started at .541169 now it's at .707297
it took me 2 days to get a basic grip of just that
.728049
what are you even doing?
ah yes now it’s understandable
hmmm this is curious
so i tried implementing built in dotenv support
but load_dotenv takes the .env from the location of where site-packages is it seems
since it's unable to load the .env
dotenv is something the user should do not the lib
i mean it would've been a nice feature to help the user along
your first argument isn't just message it's context
so it's generally called "ctx"
and then just do ctx.send
change message to be ctx.
await ctx.send(arg1)
thats error.
just not logged. anything that doesnt perform as intended is error
do you have any other commands?
You have an error handler?
or bug or unintended feature
on_message event?
hence why i asked if they have other commands
This is pretty much the wrong approach, I'd give up on attempting to really read discord.py's internals rather go to the discord API docs and go to the gateway section
Keep in mind now that since message content will become intents you want to setup slash commands impl
And it should be on an HTTP server
rather then done over websocket events
again. remove channel
Not the issue
sure? i;ve always just done ctx.send
Both can work
psh
if he wants to be inefficient fine. who am I to tell him.
let him continue to write the 8 extra characters.
Uh...
.>
That has nothing to do with you telling him it is his error in code
but there's no other thing wrong
Nothing wrong in the command itself yes
i did a mix where i tried mostly looking at the docs but also a bit at dpy's code for a slight idea on how it's done
also slash commands will come yes
just we want to get regular bot features first
since slash commands are a horrible pain in the back
Referencing discord.py code is fine imo, but one of your wrapper ideas is that discord.py code is bad, apparently from what your maintainer says
i'd recommend doing slash only bot since prefixes are going to get nerfed anyways
Then you got issues elsewhere.
parts of it
I'd just make sure to read the actual docs sometimes rather then referencing everything
Keep in mind for your slash commands impl discord wants it to be done on an HTTP server
definitely am doing so
rather then over a websocket dispatch
like i use the docs to learn how it works and if i cannot figure out how to do a step i look at other libraries to see how they did it for an idea
i haven't looked yet much but i heard that because of the HTTP server it's a real pain
Not really
its easy, just need to tunnel the ip so it isn't localhost
since discord won't accept http scheme
and is there a reason why your wrapper is under GPL 3?
Rather then MIT
at the start we were looking which one seemed good and we decided on GPL3
what is wrong with GPL3 in your opinion?
I don't see anything wrong with GPL although MIT and BSD are more permissive licenses, and that's what most libraries generally use.
Just not sure why you would choose GPL3 over MIT
it's getting slower.. aahh
nfi what happens once it ticks over..
oh. we're at 98.. 🤔
AHH
99
oh
it just ticks over to the next second. well that was anticlimatic.
every 60 seconds 1.01 minutes passes
my best guess is that it waits 60 seconds but because of processing time in between it adds 0.01
It's not that huge of a deal tbh
how can i add an embed here? py content=f"**Left Guild**\n**Name:** {guild.name}\n**Id:** {guild.id}") webhook.execute()
!d discord.Embed
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
how do i make a command that reacts to a mention?
@client.event
async def on_message(message):
if client.user.mentioned_in(message):
await message.channel.send("You text in here!")
if you mention the bot
tysm!
o///o
how do i make it as a reaction doe
message.reply
Hello, I am having an issue with my code. I am trying to figure out how to "stop" my async function while its in a middle of a for loop
Is this possible?
if roles[num] in ctx.author.roles:
author_team = roles[num]
for member in ctx.guild.members:
if author_team in member.roles:
teamNum += 1
if teamNum > supercon['teamCap']:
await ctx.message.add_reaction(Check2)
Error = discord.Embed(title="Transaction Error")
Error.add_field(name="Reason for Failure", value=MaxRosterError)
await ctx.send(embed=Error)
break
return
if FArole in user.roles:```
bruh okay discord, amazing formatting
k there, fixed the formatting
content=discord.Embed(colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
could this work
why are you passing all these params their default values?
just leave them out if you aren't going to use them?
What the
I am so confused
i mean you're making it confusing for yourself
hollon brb lemme try one
by adding all params even tho you aren't passing anything useful to them
dude what, why even create a discord embed
if ur not gonna add any values
mad confused
anyways
U got any any i can stop a an async function inside of a for loop? @valid niche
without disrupting the rest of the code
i am fixing it
Anyone knows how to manually get discord's rate-limits per route?
okay so what do you mean with stop your async function?
So as u can see
for member in ctx.guild.members:
if author_team in member.roles:
teamNum += 1
if teamNum > supercon['teamCap']:
await ctx.message.add_reaction(Check2)
Error = discord.Embed(title="Transaction Error")
Error.add_field(name="Reason for Failure", value=MaxRosterError)
await ctx.send(embed=Error)
break
return```
i attempt to stop the **WHOLE function** if this `if statement` is true
but it doesnt work so idk what to do
an its in a `for loop` if u check on the toop
also that bottom return is NEVER reached due to the break above it
oh
i thought break stop the function from REPEATING not END it
interesting..
i am so confused how to add an embed to this
content=f"**Left Guild**\n**Name:** {guild.name}\n**Id:** {guild.id}")
webhook.execute()```
break stops a loop from iterating, may it be a for loop or a while loop
break has no effect on functions
it's a loop only thing
okay
so then if i just remove break and let it return what happens?
im gonna be honest here i never took the time to actually learn was return does
the entire function stops the moment it reaches return, in this case you have no return value so it returns nothing
i just know it stops something and returns an end value lol
Oh so all i had to do was just remove break 🤣
thx for the help
can someone help? 😕
wym add an embed like this?
that's just 3 inline fields
server name and flock anti are a field
server membercount and 4 are a field
and server owner and that mention is a field
Yeah ik but how i add an embed?
you just make an embed instance
add 3 fields
and use it in the embed= field in send()
wym
when i add that should it be like this
content=embed.add_field(name="Field 1 Title", value="This is the value for field 1. This is NOT an inline field.", inline=False)```
?
right
when i put it i get this
it's on a different line
also read the error
it says invalid syntax
how i fix it?
Why are you adding a variable? I think that might be your problem but I may be wrong
i just wanna make a embed its this hard...
Ok you want to make an embed?
yes
by looking at your code and write how python should be written
syntax error means you just didn't write correct python
it's a grammar issue for programmers
tho if you don't have that knowledge, i wonder why you are even doing discord bots...
amen ^

embed=discord.Embed(title="A very simple embed", description="this is a description", colour=0xffffff, timestamp=ctx.message.created_at)
embed.add_feild(value="hello")
await ctx.send(embed=embed)
You do need to pass context and I do recommend just doing 1 Google search on how to make an embed
does need an extra ) though at the end
^^
Thanks
I need help playing sound in higher quality
why?

It skips every few seconds
dpy recommends 3.8 atleast
skipping voice audio is the fault of your own local computer not of the code
No like
pass....context?
The bot stops playing every minute

Well yes if this is in a command
I don't think this is the appropriate channel for this.
guys im just starting, i want to make kinda of a script to discord, for X to X time it sends a message for a specific channel
how can i do that
use the tasks extension
well it just doesn't exist
so i assume that should be clear
you're trying to add 1 to a value that doesn't exist
also json ehhh
i just "know" how to work with JS
!warn 849462626055487489 Not quite sure what made you think that's appropriate here, but it isn't. Please don't be posting memes here.
:incoming_envelope: :ok_hand: applied warning to @balmy gate.
error
i think you might want to delete that image before people start abusing that webhook
and regenerate that webhook
can you use heroku with the python idle
i mean feel free to use heroku, but for a discord bot it's one of the worst things you can do
how come?
read this
thank you for the advice bro
Please help.
Is it a good idea to host a bot in a raspberry pi
it works fine for small to medium sized bots
My bot has 202 it's pretty small
202 what?
For a bot that small do you think it can stay stock
Lines
Wdym?
how many guilds is the bot in?
and how many users are in all those guilds combined?
Oh my bad I didnt knew what that ment but now I do it only has 3
so that's small
And only has 16 users in all the guilds
It can stay stock right and does it even need a fan in that case ?
Where I can find button documentation?
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
!d discord.ui.button
discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View "discord.ui.View"), the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") being pressed and the [`discord.Interaction`](https://discordpy.readthedocs.io/en/master/api.html#discord.Interaction "discord.Interaction") you receive.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
there are examples inside the repo
from discord.ext.commands import *
from discord.ext import commands
class Deletechannels(commands.Cog):
def __init__(self,bot) -> None:
self.bot = bot
@commands.has_permissions(manage_channels=True)
@commands.cooldown(1,5,BucketType.member)
@commands.command()
async def delchannel(self,ctx, channel : int) -> str:
await channel.delete()
ctx.send('done deleting',f'<#{channel}>')
@delchannel.error
async def delchannel_error(self,ctx,error):
if isinstance(error,commands.MissingPermissions):
await ctx.send('you dont have Permission to execute that command')
elif isinstance(error,commands.MissingRequiredArgument):
await ctx.send('MissingRequiredArgument')
elif isinstance(error, CommandOnCooldown):
await ctx.send(f'you can try again after -> {round(error.retry_after)}s')
else:
await ctx.send('there was an error')
def setup(bot):
bot.add_cog(Deletechannels(bot))``` it doesnt give me any errors , it just goes to the else statement , perhaps i shouldnt delete channels in that way ?
you didnt pass that emoji while using the addemoji

!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
https://paste.pythondiscord.com/seqeyikopo.sql anyone know whats wrong with this?
how to add CLIENT SECRET to secrets
you've typehinted channel to an int, you'd typehint it to discord.TextChannel for channel.delete to work
@bot.command(pass_context=True)
async def afk(ctx, *, reason='AFK'):
current_nick = ctx.author.display_name
embed = discord.Embed(name="", description=f"{ctx.author.mention} is now AFK - '{reason}'")
await ctx.send(embed=embed)
try:
await ctx.author.edit(nick=f"[AFK] {ctx.author.display_name}")
except:
pass
start = time.time()
guildID = ctx.guild.id
collection = dbclient.db.users
data = await dbclient.get_array(collection, {'id': ctx.author.id})
if data == None:
await dbclient.create_doc(
collection, {
'id': ctx.author.id,
'afk': [(start, guildID, current_nick, reason)]
})
else:
try:
data['afk'].append((start, guildID, current_nick, reason))
except:
data['afk'] = [(start, guildID, current_nick, reason)]
await dbclient.update_array(collection, {'id': ctx.author.id}, data)```
i get an error for ` start = time.time()`, error: `'str' object has no attribute 'time'`
you’re overriding time somewhere
wdym
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
my whole bot source?
your doing time = "" somewhere
answer cookie’s question instead
time = datetime.now().strftime("%H:%M %p")```
??
we asked about time, not that
remove that or rename the variable
alright ty
oh alright
from discord.ext.commands import *
from discord.ext import commands
import discord
class Deletechannels(commands.Cog):
def __init__(self,bot) -> None:
self.bot = bot
@commands.has_permissions(manage_channels=True)
@commands.cooldown(1,5,BucketType.member)
@commands.command()
async def delete(self,ctx, channel : discord.TextChannel or discord.VoiceChannel ) -> str:
await channel.delete()
await ctx.send(f'done deleting <#{channel}>')
@delete.error
async def delchannel_error(self,ctx,error):
if isinstance(error,commands.MissingPermissions):
await ctx.send('you dont have Permission to execute that command')
elif isinstance(error,commands.MissingRequiredArgument):
await ctx.send('MissingRequiredArgument')
elif isinstance(error, CommandOnCooldown):
await ctx.send(f'you can try again after -> {round(error.retry_after)}s')
else:
await ctx.send('there was an error')
def setup(bot):
bot.add_cog(Deletechannels(bot))``` a new error 
how do i make my bot log whenever a user joins or leaves a voice channel
using on_voice_state_update()
you'd use typing.Union[discord.TextChannel, discord.VoiceChannel], and don't forget to import typing
import typing
channel: typing.Union[discord.TextChannel, discord.VoiceChannel]
or if you’re using 3.10 you can use TextChannel | VoiceChannel
can work also if you from __future__ import annotations
channel : typing.Union[discord.TextChannel, discord.VoiceChannel]) -> str: like this ?
yes
yes, minus the -> str because it isn't returning anything
!d discord.Guild.create_custom_emoji
await create_custom_emoji(*, name, image, roles=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a custom [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji") for the guild.
There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.
You must have the [`manage_emojis`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_emojis "discord.Permissions.manage_emojis") permission to do this.
anyone?
@bot.command(pass_context=True)
async def afk(ctx, *, reason='AFK'):
current_nick = ctx.author.display_name
embed = discord.Embed(name="", description=f"{ctx.author.mention} is now AFK - '{reason}'")
await ctx.send(embed=embed)
try:
await ctx.author.edit(nick=f"[AFK] {ctx.author.display_name}")
except:
pass
start = time.time()
guildID = ctx.guild.id
collection = dbclient.db.users
data = await dbclient.get_array(collection, {'id': ctx.author.id})
if data == None:
await dbclient.create_doc(
collection, {
'id': ctx.author.id,
'afk': [(start, guildID, current_nick, reason)]
})
else:
try:
data['afk'].append((start, guildID, current_nick, reason))
except:
data['afk'] = [(start, guildID, current_nick, reason)]
await dbclient.update_array(collection, {'id': ctx.author.id}, data)```
``` collection = dbclient.db.users
NameError: name 'dbclient' is not defined```
how should i def dbclient? never done something like this
by not copying code
yeah ik my bad
define dbclient to your database
also what are Unions ?
!d typing.Union
typing.Union```
Union type; `Union[X, Y]` is equivalent to `X | Y` and means either X or Y.
To define a union, use e.g. `Union[int, str]` or the shorthand `int | str`. Details...
it means one of the types
Odd I was able to use the pipe character for union on python 3.9.7 without import annotations from __future__
I see the pep as well it says 3.10

you like it when error
wdym ?
it was a joke
Think you forgot the verbose flag
joking but your error handler should output something helpful
import typing
from discord.ext.commands import *
from discord.ext import commands
import discord
class Deletechannels(commands.Cog):
def __init__(self,bot) -> None:
self.bot = bot
@commands.has_permissions(manage_channels=True)
@commands.cooldown(1,5,BucketType.member)
@commands.command()
async def delete(self,ctx,channel : typing.Union[discord.TextChannel, discord.VoiceChannel]) -> None:
await channel.delete()
await ctx.send(f'done deleting <#{channel}>')
@delete.error
async def delchannel_error(self,ctx,error):
if isinstance(error,commands.MissingPermissions):
await ctx.send('you dont have Permission to execute that command')
elif isinstance(error,commands.MissingRequiredArgument):
await ctx.send('MissingRequiredArgument')
elif isinstance(error, CommandOnCooldown):
await ctx.send(f'you can try again after -> {round(error.retry_after)}s')
else:
await ctx.send('there was an error')
def setup(bot):
bot.add_cog(Deletechannels(bot))``` , code so far 
rather then saying there was an error you should raise the error
in the else clause you should raise the error
oh i never knew i can 
that somehow fixed it
it didnt show the error BUT it got fixed
bruh
How can I host my bot if I am coding it on vscode?
Imo don't go for a raspberry pi
a
Command raised an exception: HTTPException: 413 Payload Too Large (error code: 40005): Request entity too large
apparently bots can't attach a file of 8mb
I'm confident its less than
someone can javascript here?
!e print(8 * (2 ** 10) ** 2)
@vast gale :white_check_mark: Your eval job has completed with return code 0.
8388608

have a wonderful day