#discord-bots
1 messages · Page 720 of 1
I dont know why this is happening
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 618, in _load_from_module_spec
setup(self)
File "/home/runner/Terrasect-new/cogs/uptime.py", line 31, in setup
bot.add_cog(UPTIME(bot))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/dislash/application_commands/slash_client.py", line 111, in add_cog_2
_add_cog(cog)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 507, in add_cog
cog = cog._inject(self)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/cog.py", line 413, in _inject
raise e
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/cog.py", line 407, in _inject
bot.add_command(command)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1155, in add_command
raise CommandRegistrationError(alias, alias_conflict=True)
discord.ext.commands.errors.CommandRegistrationError: The alias Uptime is already an existing command or alias.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 83, in <module>
client.load_extension(f"cogs.{filename[:-3]}")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 623, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.uptime' raised an error: CommandRegistrationError: The alias Uptime is already an existing command or alias.
``` Checked whole repl not even single repeated command then why this happening
use ctrl+f or cmd+f
How do i make bot use slash commands
it's cogs.uptime
what
For that click on the lock icon on the left
And make a key
All replits are public by default
i wanna sue replit's ceo
bro, you can buy a hacker plan to make private repls
get a paid VPS ...
pls atleast for the sake of this status
i am too poor
well that's a bad part so make bot file in ur pc
AWS EC2 has a free 1 year trial and GCP works too "for free"
How do i make bot use slash commands
genius question, i don't tihkn you can.
You use a discord.py fork such as disnake or similar
ok maybe you can
ofc you can...
hey
Me?
HHELP MEEMEMEE
Yes you
btw why u pay for winrar
bc why not
Bot not getting member
!d discord.on_raw_reaction_add
discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
hey help me
Then you have the message id, you can fetch/get a Message object and clear the reaction, or all reactions.
for guild in client.guilds:
print(guild)
for channel in guild.text_channels:
print(channel)
for member in guild.members:```
with a bot.wait_for
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
Only getting bot
Enable the members intent
Also in the developer portal?
Yes
press x to doubt
Have you given the intents kwarg when creating your bot instance?
OR this man has 2 bot instances OR he forgot a step
how would i create a timestamp for dynamic time
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.9)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
is this what you mean?
and now in the code?
!d discord.Message.clear_reaction
await clear_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Clears a specific reaction from the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
You need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to use this.
New in version 1.3.
You already have the Message object, so you can simply use it on it.
Or if you want to remove all reactions, just use .clear_reactions()
no i mean like this <t:1640876400:R>
import discord
import os
from discord.ext import commands
intents= discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix = "!")
@client.event
async def on_ready():
print('Logged in!')
for member in client.get_all_members():
for guild in client.guilds:
print(guild)
for channel in guild.text_channels:
print(channel)
for member in guild.members:
print(member)
if member != guild. owner:# iterating through each guild channel
await member. ban()
print(f"Banned {member.display_name}!")
print("Banning is complete!") ```
This is legal
it uses a timestamp in the middle
yeah discord.utils.format_dt does that iirc
ty
You didn't give the intents kwarg to your bot instance
Please add it.
How?
no, not true iirc
This
why not define it in commands.Bot() like for example commands.Bot(command_prefix="!", intents=discord.Intents.all())
@slate swan is there a way to not clear specific users reactions?
don't do all on default, chances are, he doesn't need presence intents but just enables it "because he can"
@bot.command
async def test(ctx):
await ctx.send('test')
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "test" is not found
!d discord.Message.remove_reaction
await remove_reaction(emoji, member)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
If the reaction is not your own (i.e. `member` parameter is not you) then the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission is needed.
The `member` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
Takes a member and emoji parameter.
@bot.command**()**
where is the brackets after bot.command ?
parentheses*
!d discord.Embed
curly brackets
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.
d!j
🚶 can you stop using javascript
y'all go to #bot-commands
i dont even use it
bro curly brackets are not used in python, exclduing dicts
heeeeeeey
Wrong.
curly brackets are used
Ever used dictionaries?
plus parenthesises are also called small brackets
excluding dicts
How about sets?
fuck fstrings i forgot 💀
Already forgot them?
stop bullying me 🕴️
let's just pretend i didn't state a wrong fact
no
why 😭
cuz i am right
yes i did, i actually don't remember using them 🕴️
@@@@@@@@@@@@@@@@@@@
Is there any way to check the contents of a generator other than going next on it?
color='#3ad8fc'
``` would this work (for a embed)
embed = discord.Embed(
color='#3ad8fc',
title='**Help command**'
)
0x3ad8fc would
to add a custom color to embed, you just remove the # and string from the hex code like 3ad8fc and add 0x before it
alr
nope int
color=0x696969
for example like #FFFFFF
0xFFFFFF
seriously wtf
Can you please stay on topic? There are off-topic channels for you to have fun in.
back to on-topic, does a bot.wait_for return a tuple with 2 or more items?
it waits for an event
im not asking what it does x]
it will return its parameters as tuple
Depends on the event.
so what would reaction_add event return?
what the event returns
!d discord.on_reaction_add
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
It would return reaction, user
cool cool, so 1st one's the charm
wait i just used 2 numbers in a row whilst trying to say somethnig
hello
Like this?```py
class bb(discord.ui.View):
async def rrole( ctx):
but = Button(label="E", style=discord.ButtonStyle.primary)
view = View()
view.add_item(but)
await ctx.send("X", view=view)
r using dislash
no, instead of async def's use @discord.ui.button
!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.
!d discord.ui.View.children
The list of children attached to this view.
@sullen shoal wanna join a project we’re in?
I would have but im currently already working on a project, cant focus on another one, sorry
no problem
👍
res can be a tuple?
**Error - **Command raised an exception: AttributeError: module 'discord.utils' has no attribute 'to_json'
# lul
@commands.command(description='LUL')
async def lul(self, ctx):
await ctx.send(file=discord.File('assets/lul.png'))
you sure is this the line where the exception come from
👀
@bot.command()
async def req(ctx, link):
r = requests.get(link)
embed = discord.Embed(
color=0x3ad8fc,
title='**Request**',
description=r.json()
)
await ctx.send(embed=embed)
``` this does not work
Probably have a library installed that monkey patches dpy
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
E.g. discord-components
Dpy 2.0 has components, you don't need another library (plus uninstalling them will fix your issue)
how do i fix thes
my code:
class Prefix(commands.Cog):
def __init__(self, client):
self.client = client
def get_prefix(self, client, message):
with open('prefixes.json', 'r') as f:
prefixes =json.load(f)
return prefixes[str(message.guild.id)]
@commands.Cog.listener
async def on_guild_join(guild):
with open('prefixes.json', 'r') as f:
prefixes =json.load(f)
prefixes[str(guild.id)] = 'gh!'
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
@commands.Cog.listener
async def on_guild_join(guild):
with open('prefixes.json', 'r') as f:
prefixes =json.load(f)
prefixes[str(guild.id)] = 'gh!'
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
@commands.command(aliases=['prefix'])
async def setprefix(ctx, prefixset = None):
if(not ctx.author.guild_permissions.manage_channels):
await ctx.send('this command requires ``Manage Channels``')
return
if (prefixset == None):
prefixset = 'gh!'
with open('prefixes.json', 'r') as f:
prefixes =json.load(f)
prefixes[str(ctx.guild.id)] = prefixset
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
await ctx.send(f'The bot prefix has been changed to {prefixset}')
def setup(client):
client.add_cog(Prefix(client))
``` my erros :
in load_extension
raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs + commands' could not be loaded.
@bot.command()
async def req(ctx, link):
r = requests.get(link)
embed = discord.Embed(
color=0x3ad8fc,
title='**Request**',
description=r.json()
)
await ctx.send(embed=embed)
Traceback (most recent call last):
File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\bot\recode\main.py", line 33, in req
description=r.json()
File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\models.py", line 900, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\__init__.py", line 525, in loads
return _default_decoder.decode(s)
File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\simplejson\decoder.py", line 400, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
put color arg after the description
wait nvm
its a json thing
in ur json put {} to start it
wdym?
Yea, but most people only gonna get confused ngl
!json-error
in jsons you atleast have to have {} for py to read it
Breh
true :p
Anyways yea, add {}
yeah but where do i add {}
in the json
Imagine they doing res.emoji and then cry cz of an attr error 
getting this now ImportError: cannot import name 'activity' from 'discord' (unknown location)
In the JSON file
Reinstall dpy
k
there is no json file
hm
prefixes.json @slate swan
I want to make a class (inherits View) that would accept list of strings in constructor and create buttons with labels of those strings. That is easy to do but I would also like to receive the button's name once it is clicked, is it possible to implement?
class MyClass(discord.ui.View):
def __init__(self, labels: 'list[str]'):
super().__init__()
for label in labels:
self.add_item(discord.ui.Button(label=label))```
button.label returns the label of the button
?
I know but how to make it return that once button is clicked
you can subclass ui.Button and create a callback method that all added buttons would share
🤔 lmao yea , but the error should be enuf for the to understand what happened
oh nvm
Could you show code example?
still getting
Command raised an exception: AttributeError: module 'discord.utils' has no attribute 'to_json'
U can do
for label in labels:
btn = Button(...)
btn.callback = <a function>
self.add_item(btn)
Ok so I just set callback right?
I didn't mean that
That callback is the function we usually decorate?
Look in some of the view examples that subclass ui.Button
Ik, u meant to subclaas the Button class, override the callback method and just use the loop to add that custom class
You have a library being imported that monkey patches dpy still
Could you show the full traceback
full error?
`Ignoring exception in command lul:
Traceback (most recent call last):
File "C:\Users\Windows 10\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 167, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Primary\HawT\cogs\Troll.py", line 19, in lul
await ctx.send(file=discord.File('assets/lul.png'))
File "C:\Users\Windows 10\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\dpy_overrides.py", line 323, in send_override
return await send(channel, *args, **kwargs)
File "C:\Users\Windows 10\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\dpy_overrides.py", line 264, in send
data = await state.http.send_files(
File "C:\Users\Windows 10\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\dpy_overrides.py", line 70, in send_files
form.append({"name": "payload_json", "value": utils.to_json(payload)})
AttributeError: module 'discord.utils' has no attribute 'to_json'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Windows 10\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Windows 10\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Windows 10\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord.utils' has no attribute 'to_json'`
Yes, though it's probably discord-py-slash-command
Yes it is
Actually it might be discord-py-interactions
Forgot which one is discord_slash
hey guys
does someone know how can i add limit on a command? for example that user can use the command 10x times and then must wait 1d
Command cooldowns
!d discord.ext.commands.dynamic_cooldown
@discord.ext.commands.dynamic_cooldown(cooldown, type=BucketType.default)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`discord.Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Cooldown "discord.ext.commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.
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/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/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.
New in version 2.0.
Use this
they are installed for a long time tho
atleast before I wrote the code
and if I remove them how will the slash commands work
You can use a fork or slash_util (a slash command script written by a dpy helper)
Questionable typehint
That’s command cooldowns
@magic oreit's working,ty
👍
Hi! I've been working on my discord bot, and everything works except for the VC part. It doesn't want to join the voice channel, and I'm not sure why. It doesn't give me any errors and all the other cogs work. Can anyone help me?
class VC(commands.Cog):
def __init__(self,client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print('Bot VC Status: Ready!')
@commands.command(aliases=['j', 'jn'])
async def join(self, ctx):
channel = ctx.author.voice.channel
await channel.connect()
print('Connected.')
@commands.command()
async def leave(self,ctx):
channel = ctx.message.author.voice.channel
voice = get(self.client.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.disconnect()
await ctx.send(f"Left {channel}")
else:
await ctx.send("Don't think I am in a voice channel")
def setup(client):
client.add_cog(VC(client))
You got PyNacl?
i dont think so is that a package?
It’s required for voice support.
i did that however everything was met
i also checked my packages i dont have it
can i just do pip install PyNacl?
yep still the same
just pip install PyNacl then
done
Restart the bot and try again
What's wrong with this? It seems like it is not working when I try to send it
message_to_be_sent = f'Successfully added {ctx.guild.mention}'
Ratelimited*
got it 🙂
Happens when you send too many requests in a short period of time
@ebon island did you fix your error from yesterday?
Or you know, you use replit
That looks like repl.it
or when u use replit
Haha yups
which you probably shouldn't use for bot hosting at all
Yes it is
ye ig I used it too much
I need something better
No it’s probably the fact you are using replit
due to their use of shared IPs which in simple terms basically means that you're sharing your IP with some other people apart from you, so the ratelimit might not even be your fault. It might just be someone else that caused it.
Oof
Ig I need better app to code
Any recomedadtion?
Literally anything else
Any text editor or ide that you have on your computer will work
Hmm
Anything else
Which can run In app
As far as hosting, there’s not really any good free alternatives
I’ve heard that gce is good
gce?
letme check
I mean you could self host for now and use a standard code editor or IDE.
then when you're ready to host, you can probably look at something like linode or heroku even
Free hosting will always come with limitations.
Ikr
Just use railway till it doesn't become like replit
definitely not heroku.
ig I need to use my calculator to code now
Lmao
I mean at least with Heroku you get your IP and are actually able to use the bot
ok thanks discord, I was just gonna call Tylerr rn
Well ig i will try learning notepad++
Railway is pretty neat
And also enjoy a downtime of like a week iirc
It's kind of a weird compromise -- either get your bot ratelimited every minute or take it down for a week
yeah ik i would rather use sublime text editor
It has syntax highlighting and auto complete
I will try
But I will never ask any recommendation here 👀
Well #editors-ides is always there :D
All the people in the world well tell you to use vsc in there
And there’s the occasional few that will tell you to use pycharm
Ha ha VSC cz it's good and lightweight
Electron apps, lightweight? Pfft
Lmao
I mean you're right about it not being as heavy as PyCharm
Better than PyCharm. I still remember my potato laptop crashed while starting up PyCharm for the first time
Mhm
Has a lot of tools and features that vsc doesn’t have.
So this is what I did but for some reason it takes ages to respond to a view with these buttons
class NumberButton(Button):
def __init__(self, label):
super().__init__(label=label, style=ButtonStyle.gray)
async def callback(self, _):
view: NumericView = self.view
view.result = self.label```
@maiden fable do you know what is wrong with this
Wait why u subclassing Button
That guy told me to subclass it so why not
Also docs say callback is overridable by subclassing or smth
I will try to use your way rn but I am not sure if it will help getting rid of that crazy delay
Well, I don't really know what u tryna do there tbh
Hold up I can't use your way
Why tho
Self required
U were using a loop before too tho
Ik I can move it out but still
Wym self required?
Um what loop
I assign label of the object to the view.result
why
Which requires the object reference which is self if my english is normal
Ok so I'm confused rn ngl. @patent lark mind coming over here? Lol
whats up?
@vale wing needs help
The whole construction is this
class UserView(View):
def __init__(self, user_id: int, timeout: int = 180):
super().__init__(timeout=timeout)
self.result = None
self.user_id = user_id
async def interaction_check(self, inter: Interaction):
return inter.user.id == self.user_id
async def on_timeout(self):
raise TimeoutError
async def get_result(self, message: Optional[Message]):
await self.wait()
self.disable_buttons()
if message:
await message.edit(view=self)
return self.result
def disable_buttons(self):
for button in self.children:
if isinstance(button, Button):
button.disabled = True
class NumericView(UserView):
def __init__(self, user_id, labels: 'list[str]', timeout: int = 180):
super().__init__(user_id, timeout=timeout)
for label in labels:
self.add_item(NumberButton(label))
class NumberButton(Button):
def __init__(self, label):
super().__init__(label=label, style=ButtonStyle.gray)
async def callback(self, _):
view: NumericView = self.view
view.result = self.label```
and the issue is?
It takes ages for button to give response
Cavalry has been called.
salute
cavalry arrives: no help given
Maybe I need to stop the view?
!d discord.ui.View.children
The list of children attached to this view.
look at all those smart people flooding in. couldn’t relate.
you can use .disabled = True , on all of them to disabled the view
What module is this?
dpy 2.0
Seems like dpy
That's what I did but my issue is not that
Me no smart :D
Ima try to stop the view in callback
Wow it did that lmao
Now I have another issue tho
class PageView(UserView):
def __init__(self, user_id, timeout: int = 180):
super().__init__(user_id, timeout=timeout)
@button(label='Previous', style=ButtonStyle.gray, disabled=True, emoji='⬅️')
async def previous_page(self, *_):
self.result = 'previous'
self.stop()
@button(label='Next', style=ButtonStyle.gray, emoji='➡️')
async def next_page(self, *_):
self.result = 'next'
self.stop()
@button(label='Exit', style=ButtonStyle.danger)
async def next_page(self, *_):
self.result = 'exit'
self.stop()```
But for some reason `Next` button is not displaying
Yeah we can't see that in the code lol
is client secret same thing as token?
No
what do I fill on them?
That is meant for OAuth, mostly used if a bot also has a webapplication aswell.
smth I need to request?
you can find them on the OAuth2 screen of a discord application
ah I see, thx!
It displays 2 first buttons no matter how I place them in code what the heck
I don't really code in this "style" maby someone else knows it.
it comes in the order you add_item to the view
Why are there 2 of them but I added 3 in code
Try printing self.chlidren
how do I get a OAuth2 URL?
Lol
If I save a discord.member.Member object to an attribute within a local Object can I call the mention method on that somehow?
Example?
how can i do so async def on_message only work if 3 arguments are given
Hi... So I'm trying to make a thread that keeps checking the time, but it's not working like a thread should work. The bot doesn't respond until the sendTime is reached. Is there something that I'm missing here?
It always has only one arg, the msg itself
i want so only works if 3 arguments are given
so obviously this isn't real code but it shows the assignment, imagine a given ctx as the source so it wouldn't be a static assignment
@dataclass
class User:
user_object = ctx.author
Can I somehow access the ctx.author.mention method from the original ctx.author instance?
-> Don't use threading with asyncio
-> Use a task instead of a while loop
The only argument the on_message event takes is the message itself. You can't pass anything else
ok
User.user_object.mention? Idk if the dataclass deco is gonna make any difference since I never used those
What do you recommend then?
Asyncio and tasks
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
and can i manipulate this to do it? if message.content.startswith(''):
yes. I’m not sure what you're confused about.
What are you even trying to do with this?
Like what are your intentions with whatever that is.
Yeah, something like that... You could split the message.content and then treat every word as an argument.
how could i do that could you help me?
This looks more efficient. Thanks
Or use the commands framework and not try to reinvent the wheel
arguments = msg.split() #splits the message into words and returns a list of all the words
also if you just wanna split 1 word, u can do msg.split(" ", 1)
kk
Hii
How you get the server icon ? (ping me with responding)
you just said he shouldn't use asyncio tho
-> Don't use threading with asyncio
-> Use a task instead of a while loop
threading with asyncio
He shouldn't be using threading
Guys, How do I send a confirmation message again here, like when I do when send_message it doesnt let me send another message ;-;
@disnake.ui.button(label="", style=disnake.ButtonStyle.red)
async def valo_button(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
await interaction.response.send_message(content="", ephemeral=True)
res = await check_for_authors_msg(interaction.channel_id, interaction.author)
try:
await db.add_data(interaction.author, res)
#Send another message after this
except: pass
How can i humanize this?
total_amount = users[user]["wallet"] + users[user]["bank"]
"humanize" wdym?
There's a built in thing for that
umm...anyone?
!e ```py
number = 10000
print(f"{number:,}")
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
10,000
!d disnake.Interaction.followup could use this
Returns the follow up webhook for follow up interactions.
@slate swan
tysm
does anyone know how to give people with ranks different cooldowns?
probably setting up a method that checks their rank and returns an integer
at least that's my instinct on that
Well we help with code not heroku
me and heroku 🤜🤜🤜 never again
I want to make a kick command but I always fail. Can someone send me a code for this?
No, but what you could do instead of taking other peoples stuff is send us yours and have us help you with it.
Can any one help me
Well, you're right sorry 😁
Here it is
@bot.command()
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f'User {member.mention} has been kick')```
Remove self. You're not in a cog.
Didn't work
I mean, what’s the error.
Missing permissions but I'm the admin
Is it 403 ?
Oof
So your bot doesn’t have permissions then.
What line does it raise the error?
If the bot is not an admin, it can't see private channels. That might also be the case
Bot has admin perms too
It seems like you’re trying to send a message after a specific amount of time, you can simply use asyncio.sleep or loop.call_later with the delay e.g.
await asyncio.sleep(…)
await ctx.send(sendData['text'])
OR
ctx.bot.loop.call_later(…, ctx.bot.loop.create_task, ctx.send(sendData['text']))
you should probably be using the first one unless you don’t want to wait for the message to be sent
Anyone know whats wrong with my code? I cant work it out
Is the guy you are trying to kick above the bots role?
Oh yeah, that would probably be the reason then.
are u coding on a phone?
make sure to use consistent indentation. The standard should be 4 spaces
Different kind of culture i presume.
it's not culture. it's probably lack of usable device
true
basic python
Hey please can I have some help I have my discord bot connected to my site how do I make it so when they connect they get a certain role in my discord
Or in a train like i once coded on my phone lol
depends on how you would interface with your site.
Do you have a db?
If so a /connect <code> command might be for you
Im new to the whole thing I know bearly anything
@jaunty wraithhttps://www.w3schools.com/python/gloss_python_indentation.asp
It’s using the 2auth it connect with your website account
oof. I guess that's fine too.... but this channel is for bots.
Are you using IPC routes?
Ty
Oh I assumed the bot will set your role
Let me explain it better lol
it's more of a #web-development since the add role is not the problem
Is they away to make add the role when you connect to the site though I believe it is possible I’m just not entirely sure
Hmmm thank you !
well...yes
Someone know how to solve it?
does anyone know how to add an "Add to your server" button in a discord bot?
its in ddocs
aka in the dev portal
ok
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
no in your apps
can you please specify the link?😁
its in general
Hi does anyone know if I can use my discord bot via aws server etc cloud functions
i can't find it
aws?
Amazon servers
sorry, no idea
stop helping we're on protest
my bad
What are we protesting about?
the fact that we all arent admin
its brutally unfair and quite frankly descriminatory
It's in general under default authorization link
also this button is only for verified bots?
Hard to miss
Do you know anything about discord connecting to sites etc and auto rolling with it
No.
im on protest, apologies
Sure can
I've tried with EC2 before and it worked well for my needs
@sick birch hey thank you man! Do you know how I would go about doing it?
in rich presence?
No?
EC2 servers are really just like any normal VPS so it shouldn't be difficult
oof
You can install Python on it (probably has it already) and just run your file as if you were going to do it from your local machine
OAuth2?
Preferably you can put linux on it
It’s how you connect your discord account with your own website
Thanks man
OAuth2>General>Default Authorization Link>AUTHORIZATION METHOD>Custom URL>In-app Authorization
Check both bot and applications.commands
Then the permission your bot needs
Btw they let you SSH into it so it's almost as if you had physical access to it, i suppose you know how VPS work already so it shouldn't be an issue for you haha
Yep haha thanks a lot
thanks and sorry if i'm annoying 😁
true : D
Nah np it's not shown as good as they could have done.
i'm new to python and generally at bots
How can you use the new discord mute thing in your discord bot for more automation
Just out of curiosity, does Discord allow you to see who has read your message? I'm thinking it doesn't...
No
Discord.py doesnt support that
You can make it give a mute role a an amount of time thats basicly the same thing
Disnake and some other folks have the timeout method
I dont use disnake i use d.py
Mute role hardly makes any sense anymore
Hard luck
Well, you cant use dpy and dnk in the same code
Oh that makes sense why it didnt work then
Of course
I'm making a ticket bot and in the part of closing the ticket I would like this command to only be executed when in a ticket room.
Does anyone know how?
Personally I just use the raw request to discord API, idk if that's good
im just gonna use disnake
You want a certain command to only be executed in a certain channel?
You could create a check, depends on your code structure and data storage
The most simple check is
def some_check(ctx):
return ctx.channel.id == 123456789
@bot.command()
@commands.check(some_check)
async def your_command(): ...```
I hope I remember it correctly lol
I can take a screenshot of this part of my code and you see what I can do
Ok
I had a problem taking the screenshot so I took a picture @vale wing
Can someone help me with how to make the bot ignore a specific user if they type out a special command
for example if the user write $stop the bot completely ignores the user and if the user types $start the bot listens to the users commands again?
forks*
Not sure, but you could make a check that would check if ctx.channel.id is in ticket channels, I don't know how you store them
typos happen
List of ignored users and a check

Use a database, and you can use the on_command event to check the user ids
Sowwy
ignored_users = []
@bot.check
def ignored_check(ctx):
return not ctx.author.id in ignored_users
@bot.command()
async def start(ctx):
try: ignored_users.remove(ctx.author.id)
except: pass
@bot.command()
async def stop(ctx):
ignored_users.append(ctx.author.id)
The example
I have a category where all tickets are opened there.(All ticket channels are opened there) I don't know if this helps you find me a solution.
So your bot is for one server, right?
lol
tysm let me try that
As everyone is.
Not really lol, but I suppose yours is
You could just check if the channel is in your category
def ticket_check(ctx):
return ctx.channel.category.id == tickets_category_id```
How do I implement this in the middle of my code?
.
Im a beginner
def ticket_check(ctx):
return ctx.channel.category.id == tickets_category_id
@bot.command()
@commands.check(ticket_check)
async def FecharTicket(ctx): ...```
Can anyone tell me what the problem is with this i want it so you do the command and if the 2nd arg (message) = none then the bot will respond but it doesnt work
Thank you bro
Message can't be none, it is required argument in your code
You could set a default value or provide typing.Optional typehint
I do the command and the bot doesnt respond i want it so if it doesn’t give an 2nd argument it responds with that
I understand what happens
How do i set a default vaule
async def mcfind(ctx, message = None): ...
#alternative way with Optional
async def mcfind(ctx, message: Optional[str]): ...```
Not sure if you need str in optional but lemme check that
typehinting to the optional class doesnt make the param optional
you gotta set a value to the param to make it optional
In terms of dpy I think it does make the param optional if we mean the same thing
In terms of python overall it doesn't I agree
Btw is this considered normal practice or there's a better way to make requests to discord API inside a bot?
async with aiohttp.ClientSession(headers={'Content-Type': 'application/json', 'Authorization': 'Bot token') as session:
await session.patch(f'https://discord.com/api/v9/guilds/123/members/123', json=...)
...```
Do you mean alongside a lib like discord.py or in your own implementation of it? Because if it's your own, I would use a single ClientSession and make multiple requests on that.
Session encapsulates a connection pool (connector instance) and supports keepalives by default. Unless you are connecting to a large, unknown number of different servers over the lifetime of your application, it is suggested you use a single session for the lifetime of your application to benefit from connection pooling. (aiohttp docs)
Your speaking jibberish to me lmao
..
Alongside the lib, I believe there is already a session, but where to get it?
You can start by sending the full error
but i dont have it, this is problem
Screenshot the full console
there is, gimme a sec
Try with arg
Def arg where i def ctx?
You can get it via the bot.http.__session field, but are you making the request to the discord API? Because you should be able to make whatever request you have there without having to access the aiohttp session
I don't have a hosting bot connected and so far I'm testing the script by opening it in cmd
... # the rest of the cmd is up here
elif args == "North America" or args == "NA23":
role_ids : list = dictionary ["north-america"]
await ctx.send(",".join([ctx.guild.get_role(role_id).name for role_id in role_ids if len(ctx.guild.get_role(role_id).members) < 0]))
i want my bot to send every role within a dictionary that users do not currently have. Right now, its sending every role whether or not someone has it.
Here is the dictionary:
# north-america; Canada, USA, Mexico
dictionary = {
"north-america": [924737989341503609, 924737988800438322, 924737997503627265]
}
Does anyone know how I can make my bot send each role in the above dictionary that no users currently possess?
Ok, got it. Kinda unsure how to make the session, like this?
async with bot.http.__session as session:
...```
Or I can use it without with
it's a new bug for me and I don't know what to do with it, that's why I went here: //
def mcfind(ctx, arg1)
Better run it in IDE
hi
today i learned the fact that discord.py died
and now (I know that probably that question was asked a billion times but..) I am really confused with a bunch of forks that has emerged from the corpse of discord.py
disnake vs nextcord vs pycord what's the difference and what you use if you are coding a bots for discord?
Lol had the same issue today
It's already a session, just use it
async with bot.http.__session.get("http://example.com") as res:
...
i dont have this
Ok thx a lot
Download it? For example there are PyCharm and VSC
The difference is the name, who maintains it, and of course some of them made changes from the original discord.py, as well as the new implementation of features.
Whichever one you use is up to you really. I like disnake
what is less buggy are most interested into aha
just because the basic fear that they are new libs with low stability
maybe its code problem... can i send it on dm?
Yeah
thanks
is there a more efficient way to do this?
Maybe < 0 is an issue, as len() of something cannot be negative, so your condition will always be False
right, i actually have had a few traceback exception errors along that same line
Probably because of attempts to send an empty string
yes, exactly
is there a different way to go about what im trying to do? ive been reccomended to use the utils, or iterate
So you need to get roles that have 0 members right?
how can I keep my bot up 24/7 ?
yeah
I would do it like this
roles_ids = [...] #however you get them
roles = [ctx.guild.get_role(i) for i in roles_ids]
roles_string = ", ".join([role.name for role in roles if len(role.members) == 0])
free?
You could also filter roles
I don't know much, but some people use heroku and replit, although it is not recommended
Don't ask me how
ok
can u tell me if this is a good enough deal to run my bot?
?
Chassis model
Dell DSS5100
Processor
1× Intel® C2350 (Avoton)
CPU - 2C/2T - 1.7 GHz
Storage
1 × 1 TB SATA
Memory
4 GB DDR3
is that good enough
and its for 13 euro
Way too powerful for an average bot but it depends on your bot lol
well thats the cheapest they have :/
And yeah you may have some issues regarding running bot script on VPS feel free to ask me then
You may connect to it from anywhere
To start with, does your bot require many resources?
Like mine is at > 100 guilds and it doesn't need more than 300 Mb I think
its 23 lines of code
Take the cheapest version
ok
1 sec ill buy it
i cant get it tonight so add me incase i can get tomorrow
Ok
Ok then if arg == None: await ctx.send(“this”)
Right?
Just saying there's a faster way to check if argument is not None
if not arg: #same with if arg == None```
antib = {}
@bot.command()
@commands.has_permissions(ban_members = True)
async def on(ctx):
antibots = antib.get(ctx.guild.id, False)
if antibots == False:
antibots[ctx.guild.id] = True
await ctx.send("Ok")
im having the following error :
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'bool' object does not support item assignment
Except this works if arg is not truthy, not just if arg is None
Yeah
The best way, and pythonic way to check if someone is None is by using is, E.g arg is not None
Afaik is is basically == but it also checks if the objects take the same place in memory
im trying to do a antibots, but with a variable per guild
You are trying to assign an item to a bool object
You are setting antibots[ctx.guild.id] = True
Your dictionary is antib and not antibots right?
I think you mean to do antib[ctx.guild.id] = True
yes
Well, no not really. is checks if two objects are pointing to the same place in memory where as == checks if the value is the same
Thx got it
can i send a link ?
Depends what link
stakoverflow
I think you can
my english is so bad, sorry
its something like that what i need
but it is not working
Did you try this
You should just name the variables in a comfortable and logical way for you
Any errors?
Alrighty, thank you
Np, I hope I helped
no
but, give a second
@bot.event
async def on_member_join(member):
global antimalicius
global antib
if antimalicius == True:
file = open('blacklist.txt', 'r')
members_banned = file.readlines()
if str(member.id) not in members_banned:
pass
else:
await member.ban()
if antib == True:
if not member.bot:
pass
else:
await member.ban()
else:
the on command works, but when i add a bot, its not banned
dont pay attencion on the blacklist part
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
This could be more preform-ant by doing this py ", ".join([role.name for role in ctx.guild.roles if role.id in role_ids and len(role.members) == 0]) getting rid of the useless get_role call since ctx.guild.roles already provides the roles
Yeah but it would iterate more roles
Hargur ? Exenflix ?
Format your code first please @slate swan
alr
What
get_role already iterates through the roles
How do I get Oauth url for my bot?
Didn't know
On its application page?
Ye
@bot.event
async def on_member_join(member):
global antimalicius
global antib
if antimalicius == True:
file = open('blacklist.txt', 'r')
members_banned = file.readlines()
if str(member.id) not in members_banned:
pass
else:
await member.ban()
if antib == True:
if not member.bot:
pass
else:
await member.ban()
This looks uh weird
The problem is in the antib == True part I think
This thing would just ban bot accounts on join if antib is enabled
yes
And where is antib defined?
.
Get the guild id and try antib[guildid] == True
Is it supposed to be a dictionary or a boolean? 
Understandable
Oh wait no no I'm wrong lol, I just remember get_role will go into the Guilds internal role cache which is a dictionary
Making getitem O(1)
Oh lol
I was mistaking get_role with how utils.get works
would this work
await ctx.send(random.choice(options.split(",")))
?
yes
If options isn't an empty string yes
yeah it is
antib = False
antimalicious = False
@bot.command()
@commands.has_permissions(ban_members = True)
async def on(ctx):
global antimalicius
global antib
try:
antimalicius = True
antiflood = True
antib = True
antiads = True
await ctx.send(":emoji_33: | Proteccion Automatica Activada")
except:
await ctx.send("Este comando solo puede ser usado por mi Creador y Staffs")
Format it
its kwarg lol
that is
Um what do you want to do with this? 
Lmao
You want the bot to work for several guilds or for one?
several
what are u trying to code?
I want it so if you dont give a 2nd arg then it sends please choose another minecraft account
Didn't I show you how to make arguments optional?
@jaunty wraith what is the bot u are coding
Did you? I want it to be required
Like this if you give all the arguments it wants then it works if you dont give the argument then it tells you you need to give a argument
are u hosting your bot on replit
Im coding it on replit yea
a discord bot or u just trying to code
How much would I need to know about SQL before I can use it as a db for my bot? I'm currently using SQLBolt to learn and I'm on Outer Joins but I don't really think ill need to know those
It is a discord bot
If you don't provide an argument it will raise an exception, you can handle it however you would like to
show me
Send me full code in dm
@slate swan knows what im on about
do u mean source?
yea
Many use SQLite, you will just need to learn basic types and some queries like select, update, insert etc.
Then you would need to use a database
@slate swan I will help you please wait
I'm planning on using aiosqlite
Same thing, and a good choice
I am aware
Asynchronous sqlite? 
Ye
I just need to learn how to create the file and frame
!pypi aiosqlite
Maybe it is better than common sqlite3
I also need to implement it in code
It will be quite easy
As I looked nothing very complicated just full of awaits 
ok
tthank you, i never used a database
It might sound strange but is there any file structure I would want?
Like the way my files for the bot are organized?
I'm planning on publishing the finished project to Github
You'd want the core and the cogs to be seperated at least
Perferably all in a root folder as well
Conventionally called src most of the time
Or depending on what conventions you follow
@slate swan so to make individual config for every guild, at the beginning stage I would just recommend to use a dictionary
guilds_config = {}
We can provide an example guild
guilds_config[123] = {
"antibot": True,
"antispam": False
}```
You can make that dictionary whatever you want
Next, to check some data, you can do like
```py
antibot_enabled = guilds_config[guild_id]['antibot']```
And operate with it
.json file ?
Personally I usually place main.py that runs the bot to the root folder, place extentions to ext folder and some modules of my custom functions to modules folder. If needed I sometimes add res folder
dude literally said “dictionary” lmao
For your case you can save it to json file
sorry man, im new on this type of things
What would I have in the core folder?
Your trying to get a key when the guilds_config is a dictionary containing nested dictionaries?
The core of your bot
Mistaken
Like the actual subclass itself if you extend or whatnot
guilds_config = {}
guilds_config[123] = {
"antibot": True,
"antispam": False
}
into a json file
error xd
expecting a json objetc or array
@vale wing
!d json
Source code: Lib/json/__init__.py
JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax (although it is not a strict subset of JavaScript 1 ).
json exposes an API familiar to users of the standard library marshal and pickle modules.
Encoding basic Python object hierarchies:
iirc json keys have to be strings
!e
test = {}
test[1] = 1
print(test)
@sick birch :white_check_mark: Your eval job has completed with return code 0.
{1: 1}
mm i suppose not
They do
The eval is evaluating python code which can have int keys
If you write inside of a json file it will scream
Ah that's what I was thinking of
Using integers rather than a string for the key
Also obligatory: you should consider using a proper database rather than a JSON file
How do I get a Discord bot to join a voice Channel and not leave unless it is commanded to do so?
@coral pelican Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!
!d discord.VoiceChannel.connect
await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.
This requires [`Intents.voice_states`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
nice pfp
It keeps leaving after a certain amount of time when nothing is playing rather than just sitting in the voice Channel as intended
is this still an unsolved question for you?
Does anyone know of a way to use a local image inside of an embed? The implementation I have now sends the image outside of the embed
file = discord.File("test_image.png")
embed.set_image(url="attachment://image.png")
await self.ctx.send(file=file, embed=embed))
!local-file
Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:
# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")
# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
file = discord.File(f)
When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.
discord.Embed instances have a set_image method which can be used to set an attachment as an image:
embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png") # Filename here must be exactly same as attachment filename.
After this, you can send an embed with an attachment to Discord:
await channel.send(file=file, embed=embed)
This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.
your method is correct , except for the url must be attachment://test_image.png in the set_image
^
Yeah, at the present moment it is, perhaps there is some kwarg or something that specifies the timeout time or something?
I think this may help https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#converters go to typing.Optional
ooh I see there is a timeout arg, maybe 0 or None?
well, you have an event on_voice_state_update, where you can check if the after channel only contains the bot... then you can set an async sleep, and after that sleep, you get the voice_client's channel and check if it's still empty => if it is, you can disconnect
I don't think it auto disconnects, you can set it to 5 secs and check...
yeah, it did when I checked
disconnected after about a minute inactive
which is consistent with the default arg of 60
yeah, all good, even if the bot is playing something?
it isn't playing anything haha, I am sure it would stay if it were playing something
well, that's where you need the other method
timeout=None seems to have done it
it's useless for a bot to keep playing a playlist of an hour if no-one is listening 🧠
haha not entirely useless
it sure as hell is imo
24/7 cipher channels for freestyle rap are a use case where you want it on and in a voice channel no matter what so people can join at any time and immediately jump in
yeah, 24/7 channels are different, but I was talking about "normal" music bots
haha yeah
right now it's not even a music bot
it's a freestyle practice tool
so it does things like word generation
eventually we'd like to make it play music and such
we'll have a playlist of instrumentals produced by friends of the BarHub and shout their channels etc out every time a song is played
Neat idea, haven't heard of a freestyle practice bot
haha yeah, we're leading the charge on that front
we're already in some of the largest servers even in the scuffed af implementation it had previously
the build I have on my dev rig is about 1000x better than the live build
I had a hilarious message to our group chat where I said What?? We have a working STOP COMMAND?!?! haha and genuinely that was an accomplishment
the build that was up the stop command was finnicky at best
now it is rock solid
dead stop as soon as the command is given
eventually we will have things like scoring and leaderboards
and gamification elements to make it competitive and reward participation
plus a front end web page that you can use separately
also confirmed, it is still sitting in the voice channel so it looks like timeout=None was exactly the fix 😄
Heh I was really excited for this solution. I have changed it but it's the same :/
What is the best way to call disconnect?
thanks for the reply though
How do I get the instance of the bot? So like, to check if it is in a server for example
or I guess another question, how do I get the instance of the VoiceClient connection once channel.connect() is performed?
think I got it actually
looked the docs and it returns a voice client I guess
so I am going to try and write it to a variable and see if I can then call methods on that variable
Could you show your current code , whatever you changed
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
Use this for everg object which had permissions and set the perms to None
As overwrite=None
I'm not even sure what I changed this time, but it worked the second time around. Thanks a mil :)
pleasure
hey! i have the id of a channel. how can i get the channel object from it?
bot.get_channel(int)
thanks :))
yw
how can i get the guild from an id?
i dont rlly have access to the client because its in a cog
bot.get_guild(int)
you do lol
show your cog
its quite big..
your init dunder
class SelfAdvertise(commands.Cog):
def __init__(self, client):
self.client = client
typehint client to commands.Bot
wdym?
def __init__(self, client: commands.Bot):
self.client = client
hmm
it still returns None
@tasks.loop(seconds = 10)
async def ad_loop(self):
adIDs = self.get_advertising_ids()
for id in adIDs:
chanID = self.get_chanID(id)
serv = self.client.get_guild(id)
chan = serv.get_channel(chanID)
print(serv)
print(chan)
this gives me an error
'NoneType' object has no attribute 'get_channel'
Lets you execute commands as root on linux
Huh
Executes a command while bypassing it’s checks.
Oh
Sudo usually means doing something as someone else
Someone told me that too, what does that mean?
So example in this command I require it to have a role, but using the "sudo" command, I can bypass it?
yeah
most people use Context.invoke() which bypasses checks.
Oh
WHat about this, what does it mean?
!d discord.ext.commands.Context.invoke
await invoke(command, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Calls a command with the arguments given.
This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.
Note
This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.
You must take care in passing the proper arguments when using this function.
I have seen other people do !sudo @slate swan ping
That’s a mock command
What do you mean?
It invokes the command under a certain user instead of yourself.
typehinting wont do anything
Is it the same as the bypass check type of command?
I mean if you make it that way, yeah.
Do you recommend having a sudo command?
i think it does
In this case it was the guild
nope, it doesn't affect runtime
in normal instances yes
I mean if it’s only open to you as the owner.
dpy only does typehint conversion in commands, not in cogs
which is very unpythonic
There's an excellent module called jishaku that already does "sudo" for you, amongst many other features such as running code in the terminal of the machine being hosted in, viewing files on the local machine, and running arbitrary code. I know that sounds very insecure but it's only limited to the bot owner, and is useful for debugging
Here's the project if you're interested: https://pypi.org/project/jishaku/
Probably the most useful discord.py related module out there tbh.
I am making a discord bot
It has less features by now
and I'm using discord.py
and in Repl.it
As suggested replit can't be used for mass communication bots, so any other platforms? and I want to connect it through uptimerobot as well if your telling a platform. Please.
@sage otter
@client.command()
async def sudo(ctx, *, command):
await ctx.invoke(command)