#discord-bots
1 messages · Page 494 of 1
that's because you don't have any ctx param in a command? the error legit tells u what it is
...
maybe the guild being nonetype
or the name being wrong
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
but i have it
what?
what i do now?
and where exactly is your message in your command?
I have no idea what your role is, what name it has, what's your guild instance
its a simple test role
I DON'T KNOW I THINK ATOM IS SOME TYPE OF SHIT
i have no message arguments in my message
the only one is
{username}
what should i do =(
u should really learn some basic python, the error is really crystal clear 🤦♂️
but basically, your message.author becomes ctx.author
message.content becomes ctx.message.content
message.channel becomes ctx.channel
also instead of splitting the author, just do .author.name
how is this undefined?
print guild and role both
right, for option in self.options
if they both exist, only the name could be wrong
oh yea
make sure it's right, since it's case sensitive
you are right
¯_(ツ)_/¯
it works now
just say
can i ask wheredid you learn this much aabout discord .py
docs
only docs ?
just see and leave
but your problem wasn't dpy related, your error was telling u what you did wrong yet u blamed your IDE when it was your lack of knowledge about python
bruh then send it
yes, you have everything you need for the lib in the docs, the rest is just your python knowledge and imagination
you are goddamn right
¯_(ツ)_/¯
lmao
ok good bye
you just learn from trial and error and the docs
^
yes that's right
I have learned/am learning from just diving in, learning the basics then trial and error
if atom's owner is in this chat i want to say sorry to him for calling his IDE shit (btw it's so good and i like it )
How can I send an embed?
ok so, im trying to use sleep_until but it instantly sending the result, idk if im doing it wrong, but heres the code:
import discord.utils
from datetime import datetime,timezone
time = datetime(2021,9,24,hour=2,minute=44,tzinfo=timezone.utc)
await discord.utils.sleep_until(time,"hi")
make a discord.Embed instance and send it
using send(embed=yourembed)
he probably isn't....
embedVar = discord.Embed(title="The Title ", description="Description" color=0x00ff00)
embedVar.add_field(name="Chat Commands", value=("The Value"), inline=False))
await ctx.send (embed=embedVar)
idk why I asked only about the embed, didn't specify the video part lol
So you want the video to embed like YouTube links do when you send them?
Yeah exactly
ignore my messages and edits my brain is not working today lol
that’s not possible. The only thing you can put in the embeds image attr like that are gifs.
I see
Thanks
um other than the muted role theres now way to mute a ppl??
Remove their permission to send messages?????
yeah ok ty
Any clue why it isn't letting me edit my file? I'm new to github by the way.
What
cant relate where this pops up
Hi i need help in my code, i create a "AntiFlood" when someone make flood the bot mute the user during 2min and later bot remove the specific rol, this works fine if I put in the code if message.author.guild_permissons.administrator: return
But when i put if ROLE in member.author.roles: return the bot mute the user with this role, anyone know how to fix it?
My Code =>
https://paste.pythondiscord.com/jiluligiwu.properties
It looks like you're already just fetching the roles from the author's role list, so couldn't you just do
if any((ADMINISTRADOR, MODERADOR, HELPER, AMIGXS)):
```or something similar?
or no
nvm thats the guild role list
Didnt work (bot.process_command without s gave an error)
Check to make sure you are actually getting the role objects
how can i add kwargs
To what?
The bot get the roles fine, 0 problems, im going to try
if any((ADMINISTRADOR, MODERADOR, HELPER, AMIGXS)):
to @quaint axle.command() commands like help or something
Well, no that would only work if it was how I mistakenly thought it worked
You mean like this? Because if so, no
!command arg1=value
unless yo make your own system
click edit file, if that doesn't work then you do not own the repository
I just waited a bit and it worked but thanks carrot :)
np
uh no
Same think, mute the user with this roles
and if i put
if message.author.guild_permissons.manage_messages: return```dont work
guys i need help with command ideas, my bot is a private multi-purp bot to both manage and entertain the members of my server so any type of command is welcome (as long as it's somewhat short and useful)
@quaint axle .command()
async def help(ctx ):
any help pls
i ge tproblem in it
this problem
await coro(*args, **kwargs)
File "C:\Users\Mohamed_Zeton\Desktop\JOB 1\job.py", line 11, in on_ready
async with open("ticket_configs.txt", mode="a") as temp:
AttributeError: __aenter__```
You could also just use the has_roles and has_permissions decorators
Or, no...
Might need to make your own check to negate those
I don't see any example of what you mean by using kwargs
open does not use asynchronous context managers
what ?
async with open("ticket_configs.txt", mode="a") as temp:
```This is the line that shows the error
To what? Embeds? commands.Bot?
But that's strange that it shows a different line in your code
do u mean arguments or keyword arguments
open doesn’t return an async context manager
Yes, that's what I said
oh sorry didn’t see above that it wasn’t your error
Looking at your pastebin though it should work, because you have
async with aiofiles.open("ticket_configs.txt", mode="a") as temp:
pass
got it working thanks
jss
yes
lol
do you maybe how fix
no, idk about js
js
i only know one thing about js.. it's for frontend web dev.
kek
hm
hello
i have a bot that give perms to channel i want it to give per to everyone sendmsg false
how do i do that
i have this code it give perm to ppl who react to msg and open them a new channel and set there perms but doesnt set everyone perms too
await ticket_channel.set_permissions(payload.member, read_messages=True, send_messages=True)```
any help
like if i change payload.member to everyone.member does it will work ?
!d discord.Guild.default_role
property default_role: discord.role.Role```
Gets the @everyone role that all members have by default.
payload.member to YourGuildInstance.default_role
guildinstance ?
just some guild object
guild = bot.get_guild(payload.guild_id)
then you just get the member role wtf
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
like i change it to like this
so like this
still didnt understand
i have role called fola i want to give it per to the channel not to read and send msg how can i do that ?
this is my question
@bot.event
async def on_raw_reaction_add(payload):
if payload.member.id != bot.user.id and str(payload.emoji) == u"\U0001F3AB":
msg_id, channel_id, category_id = bot.ticket_configs[payload.guild_id]
if payload.message_id == msg_id:
guild = bot.get_guild(payload.guild_id)
for category in guild.categories:
if category.id == category_id:
break
channel = guild.get_channel(channel_id)
ticket_channel = await category.create_text_channel(f"ticket-{payload.member.display_name}", topic=f"A ticket for {payload.member.display_name}.", permission_synced=True)
await ticket_channel.set_permissions(payload.member, read_messages=True, send_messages=True)
await ticket_channel.set_permissions(fola.member, read_messages=False, send_messages=False)```
guild = bot.get_guild(payload.guild_id)
role = guild.get_role(role_id) #replace role_id with your role's id
await ticket_channel.set_permissions(role, read_messages=True, send_messages=True)
so it should be like this ?like i sent ?
fola is a role
an undefined error
hello im currently having issues editing an embeded it edits the message and adds this <discord.embeds.Embed object at 0x00000218FC8394C0> with this code await meani.edit(embed=embeded)
So I have this task which is changing my bots status```py
class Events(commands.Cog):
def init(self, bot):
self.bot = bot
if self.bot.config.testing is False and self.bot.cluster == 1:
self.bot_stats_updater = bot.loop.create_task(self.bot_stats_updater())
self.bot_misc_updater = bot.loop.create_task(self.bot_misc_updater())
self.status.start()
@tasks.loop(seconds = 10) # minutes = 5
async def status(self):
statuses = cycle([f'{self.bot.config.default_prefix}help', f'{self.bot.config.activity}', f'<t:{int(self.bot.user.created_at.timestamp())}:R>', f'Gateway latency: {round(self.bot.latency * 1000, 2)}ms.', f'CPU Usage: {psutil.cpu_percent(interval=None)}%', f'RAM Usage: {psutil.virtual_memory().percent}%', ])
await self.bot.change_presence(activity = discord.Game(next(statuses))
@status.before_loop
async def before_status(self):
await self.bot.wait_until_ready()```but I keep getting this error```py
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.events' raised an error: SyntaxError: invalid syntax (events.py, line 39)```but i'm not sure why, is wait until read supposed to be inline with the task itself
so which line is this
line 39 is async def before_status(self):
mmhmm
missing ) in previous line
because it kept expecting it until it found an expression
changing presence every 5 minutes
or something like that
no that’s actually 10 seconds
I hope he's gonna change it
5 minutes is commented
since that comment's there
noticed
but he'll surely change it
right @flat solstice? 👀
He probably will change to 5 sec
yeah fixed that now, hoping it's not gona break on something else
yeah i'm gonna make it 5 min, secs is too short for me
how i can remove all reactions form message bot
TypeError: 'NoneType' object is not iterable```
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
let's check this
this does not make sense
cur.execute('SELECT User, Language FROM lang_store WHERE User = ?', (user,))
row = cur.fetchone()
row = list(row)
print('help', row)```
yep, this gives u a list
I would iterate through that
but that's prolly dumb
are you talking about me
no
i don't understand this
for example you do
i just need remove all reactions from bot message
hm
!d discord.Message.clear_reactions
await clear_reactions()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes all the reactions from the message.
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.
this better ye?
ye
why it not work?
Is there someting to do before i can do the .get_user ???
I think just make sure you've got member intents enabled.
!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.
hello im currently having issues editing an embeded it edits the message and adds this <discord.embeds.Embed object at 0x00000218FC8394C0> with this code await meani.edit(embed=embeded)
from discord import *
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=".", intents=intents)
m = bot.get_user(286776720449601537)
print(m)
///OUTPUT: NONE
Please help 🙂
Are you running the bot at all?
Yes, not all the code
I had trouble with editing channel names... But it was a limit on how often you could edit channel names, like 10 minutes apart. Might be something like that
So you have bot.run("bot token") at the end of your code?
What is the value of embeded?
from discord import *
from discord.ext import commands
from database import *
TOKEN = "x"
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=".", intents=intents)
def send(ticker, text):
mycursor.execute(f'''
SELECT user, quantity
FROM user_stock
WHERE ticker = '{ticker}' AND quantity > 0
''')
result = mycursor.fetchall()
for i in result:
r = i[0]
mycursor.execute(f'''
SELECT discordId
FROM user
WHERE id = {r}
''')
result2 = mycursor.fetchone()
print(result2[0])
m = bot.get_user(286776720449601537)
print(m)
send('FTHF', 'h')
bot.run(TOKEN)```
You can't use bot methods until the bot has started, im pretty sure
get_user gets the user from the bot's cache, which dosen't exist yet really
NS...
embeded=Embed(title="Tests", description="Testing")
I assume that the user is not found in the bot's cache. You are executing the function before the bot runs.
You can call the function inside an on_ready event.
!d discord.on_ready
discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.guilds "discord.Client.guilds") and co. are filled up.
Warning
This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
ooooooooh
And meani is a message object, yes?
Can you send where you get that from?
THanks!!!
yes i can change the value of embeded and the message will change but it will keep having <discord.embeds.Embed object at 0x00000218FC8394C0> at the top of the message
No problem.
it edits fine but just has <discord.embeds.Embed object at 0x00000218FC8394C0> at the top and idk why
Do you mean it has the embed and <discord.embeds.Embed object at 0x00000218FC8394C0>?
Because that would mean that you are passing the embed as the content in the original message
Send the code for when you first send the message
when the embed is first sent it doesnt have <discord.embeds.Embed object at 0x00000218FC8394C0> only after editing it has that
Can you send your whole code for this command?
Try await meani.edit(embeds=[embeded]).
discord.py is dead?
You're too late.
There's no embeds kwarg for edit
?
It's not dead just yet, just not getting updated anymore
Any further changes to the discord API will not be applied to discord.py
no
Why? That affect the bots?
!pypi dislash.py
dislash.py is an interactions library
it's not a fork. disnake is what you're thinking of
Oh right. I meant disnake.
thank you i fixed it i regenerated the embeded and then it just worked lol
if it’s a breaking change it could
!pypi disnake
i mean if it’s a breaking change it’s probably going to be on another api version
This task I have for changing my bots status doesn't seem to be working. It sets the status when the bot launches when it doesn't seem to be changing the status and I've been waiting 5 - 10 mins now but it doesn't seem to be erroring```py
class Events(commands.Cog):
def init(self, bot):
self.bot = bot
if self.bot.config.testing is False and self.bot.cluster == 1:
self.bot_stats_updater = bot.loop.create_task(self.bot_stats_updater())
self.bot_misc_updater = bot.loop.create_task(self.bot_misc_updater())
self.status.start()
@tasks.loop(seconds = 30) # minutes = 5
async def status(self):
statuses = cycle([f'{self.bot.config.default_prefix}help', f'{self.bot.config.activity}', f'<t:{int(self.bot.user.created_at.timestamp())}:R>', f'Gateway latency: {round(self.bot.latency * 1000, 2)}ms.', f'CPU Usage: {psutil.cpu_percent(interval=None)}%', f'RAM Usage: {psutil.virtual_memory().percent}%', ])
await self.bot.change_presence(activity = discord.Game(next(statuses)))
@status.before_loop
async def before_status(self):
await self.bot.wait_until_ready()```
I'm not a professional at iterators, but I believe it might be because you are re-defining your iterator every time, so next() will return the same value each time
The iterable restarts each time the task executes
hmm makes sense
what would be a good way to fix this, Would a different task defining the list work and then use the current task to iterate it?
You could define it somewhere else where the iterator would change, but not be redefined, such as an instance variable
def __init__(self, bot):
# do ur stuff
self.statuses = cycle([...])
@tasks.loop()
async def statuses(self):
next(self.statuses)
I was thinking about that however I'm not sure it would work since i'm doing these and I'm not sure if they will work in the initialisationpy f'{self.bot.config.default_prefix}help', f'{self.bot.config.activity}', f'<t:{int(self.bot.user.created_at.timestamp())}:R>
Ah, yeah, then put them in your before_loop, after the wait for ready
so if i'm understanding you correctly then something like this```py
class Events(commands.Cog):
def init(self, bot):
self.bot = bot
if self.bot.config.testing is False and self.bot.cluster == 1:
self.bot_stats_updater = bot.loop.create_task(self.bot_stats_updater())
self.bot_misc_updater = bot.loop.create_task(self.bot_misc_updater())
self.statuses = []
self.status.start()
@tasks.loop(seconds = 30) # minutes = 5
async def status(self):
await self.bot.change_presence(activity = discord.Game(next(self.statuses)))
@status.before_loop
async def before_status(self):
await self.bot.wait_until_ready()
self.statuses = cycle([f'{self.bot.config.default_prefix}help', f'{self.bot.config.activity}', f'<t:{int(self.bot.user.created_at.timestamp())}:R>', f'Gateway latency: {round(self.bot.latency * 1000, 2)}ms.', f'CPU Usage: {psutil.cpu_percent(interval=None)}%', f'RAM Usage: {psutil.virtual_memory().percent}%', ])```am I misunderstanding?
Yah, that's what I mean
okay cool
yay it's finally working, thanks for your help it's greatly appreciated
Why does the bot needs a link to play a song?
Code
@commands.command()
async def play(self,ctx,url):
ctx.voice_client.stop()
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
YDL_OPTIONS = {'format':"bestaudio"}
vc = ctx.voice_client
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info['formats'][0]['url']
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
vc.play(source)```
green discord
what
@glacial swan is green discord
No
I am asking the question
I've set a botvar bot.cluster in bot.py and now I'm trying to access it in a cog but it says that bot doesn't have cluster attribute.
def __init__(self, bot):
self.bot = bot
self.guilds_db = bot.cluster["GX"]["guilds"]
you’re probably loading the cog before setting the attribute
@bot.command()
async def vote(ctx, *args):
if (startdict[ctx.author]) == 0:
await ctx.send ("Please Do .start")
else:
if len(args) == 1:
if (args)== ("A"):
print ("A")
elif(args) == ("B"):
print ("B")
elif(args) == ("C"):
print("C")
else:
print ("Enter a valid vote")
elif len(args) == 0:
await ctx.send("A, B, C")
else:
await ctx.send("Enter a valid vote")
Can someone help me, no matter what I send as a vote, it sends enter a valid vote, even if I do A, (Ignore the .start part, that doesn't matter)
try printing the args variable
you'll probably see what is wrong then
ok
you'd do async def vote(ctx, *, args: str): the typehint is optional
no need for the typehint
It still doesn't work
it's good practice to be explicit with your typehints
discord.py defaults it to str anyways
it's good practice to be explicit with typehints
what is a type hint
I love a typehint personally
text: str =
oh ok
you specify what type the value is expected to b e
the typing library has a lot of tools for this too
!d typing
New in version 3.5.
Source code: Lib/typing.py
Note
The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.
This module provides runtime support for type hints as specified by PEP 484, PEP 526, PEP 544, PEP 586, PEP 589, PEP 591, PEP 612 and PEP 613. The most fundamental support consists of the types Any, Union, Tuple, Callable, TypeVar, and Generic. For full specification please see PEP 484. For a simplified introduction to type hints see PEP 483.
The function below takes and returns a string and is annotated as follows...
its the : str it usually doesn't affect the program at runtime, but in d.py it is used for converters
Uh, sry for being annoying but I did what u did and it still doesn't work
@bot.command()
async def vote(ctx, *args: str):
if (startdict[ctx.author]) == 0:
await ctx.send ("Please Do .start")
else:
if len(args) == 1:
if (args)== ("A"):
print ("A")
elif(args) == ("B"):
print ("B")
elif(args) == ("C"):
print("C")
else:
print ("Enter a valid vote")
elif len(args) == 0:
await ctx.send("A, B, C")
else:
await ctx.send("Enter a valid vote")
this is what it looks like now
args is still a tuple
I changed it to a str
remove that * and make it a kwarg
ok
it doesn’t matter if you keep the *
Why does the bot needs a link to play a song?
I want it to be able to recognize when someone sends a msg with no arg tho
give the parameter a default value
if you can’t understand that, you should learn more python
anyone?
async def vote(ctx, args = "default value here"): but yes you should learn more python
I prob should
yes you should
is there a website that would be good at teaching me
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
k thx
today is the day that I learned bots can make servers
if your bot is in less than 10 servers yea
so it can actually get the songs content to play it
if user_message.lower() == '*revive':
await message.channel.send('Revive the chat!')
await message.channel.send('@Chat Revival')
return
its not pinging the role
how i do it
Discord will interpret that as a string, you can do this
role = ctx.guild.get_role(role_id)
await message.channel.send(role.mention)
k
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send(
content=f":x: Command `{ctx.message.content.split()[0]}` does not exist.",
delete_after=3
)
else:
await ctx.send(f":x: Unknown error!\n'{error}'")
how do I improve this error handler
you can use get() function from discord.utils
Can u put a button in a embed
using discord_interactions
the official discord.py doesn't have that, you have to use a third party module
can u send me the link
the official discord.py also doesn't have discord slahs commands
discord.py v2 has buttons
you can install it with pip install discord_interactions
idk theres a v2 version of discord.py :P
!pypi discord_interactions
there we go
there is you just have to install it from github
and not pip ||(or pypi)||?
nope installing with pip will install discord.py 1.7.3
you can use pip also to install v2
rlly?
here
im trying to get the html from a youtube search for a music bot with urllib3 but does anyone no why it is not returning the full html file?
ohhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
i guess you can 🤔 i just did this before
git clone sucks
no more music bots
they cloned the package name + directory name
ok
its for learning purposes only, im not bringing it to public or anything, or did youtube change it so that it blocks it
oh i see
use their api
@ionic path but i mean like buttons inside the embed
I think you can use interactions link
where if you click the lnk something happens
you can do CLICK ME FOR HELP
it only works on bots tho
Currently there is no way of doing so like the link the embed on the discord invite links
may someone know why it is doesn't work?
dunno
?
can you please send the text code in here
because its hard to type it all like that
what is the error
and output
@client.command()
async def give(ctx, mins: int, *, prize: str):
embed = discord.Embed(title=f"Giveaway started", description=f"{prize}", color=discord.Colour.random())
end = datetime.datetime.utcnow() + datetime.timedelta(seconds = mins*60)
embed.add_field(name=" Ends At:", value=f"{end} UTC")
embed.set_footer(text=f"Ends {mins} mintues from now!")
my_msg = await ctx.send(embed=embed)
await my_msg.add_reaction("🎉")
await asyncio.sleep(mins)
new_msg = await ctx.channel.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(client.user))
winner = random.choice(users)
await ctx.send(f"{winner.mention} won {prize} the prize!")
try to give people more info like an error message if you have one
it works fro me perfectly
:P
how.
there is no problems
with the thing
👌 it works perfectly
dam so why it's don't work for me
is there an error?
tell me whats the error in the console
i have nothing in the output
I think you can also do pip install git+https://github.com/Rapptz/discord.py@750ba88f2c9d1d51ecf3accdd325bd83aa8ae95b
and
except Exception as err:
print(err)
also add that
and look at the console for output
you must have a error handler that doesn't show what is the error and just straight up just raise the error
do you have this line?:
@client.event
async def on_message(message):
(code here blah)
If so maybe you did not add
await client.process_commands(message)
at the end
or maybe he's talking about this
the giveaway ended so quickly
its supposed to be minutes
it turned into seconds
yes but when I started I forgot to put await bot.process_commands(message) at the end of the on_message event which made it so that for some reason the bot does not process commands
In discord.py how to add reaction through message ID
ID is int
so it doesn't have attribute add_reaction
msg = get(ctx.channel.messages, id=msg_id)
await msg.add_reaction("👍")```
thnx so much
you're welcome.
Wait but there's no attribute called get
However this does work
how do i use paginator?
yes
sorry for replying late I was washing the dishes
It was a fun time....
Not related to Code, but how can I modify a followed channel in my server so whenever it updates it will automatically ping a role
Hi, I wanted to change a channel name automatically every 1 minute or so. How can I do that? I only need the thing for the change channel name
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").
Yes I know how I will do the loop. But I want to know how I can change the channel name of a specific server with what I provide
Channel. A Voice Channel
!d discord.Client.get_channel you can use this to get the channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
and then use .edit to edit it
Ohh okay
!d discord.VoiceChannel.edit
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
Thank you
Np
Not related to Code, but how can I modify a followed channel in my server so whenever it updates it will automatically ping a role
When you have followed a channel for your server? Or when someone follows your channel
Former
Ox800080
you need to use 0x before the hex since # are comments in python
ohh
forgot thank you so much
i cant fix this colorama error
it just prints
@slate swan
Are voice commands a thing?
No
I'm not familiar with that specific error. Is there any details you can add?
*are
How do you get the image ? Some api
Ah
Get the VC channel object with guild.get_channel()and do await channel.connect()
Bro... You hid the traceback error
@bot.command()
async def announce(ctx, *, content, titlee=None, footerr=None):
if content is None:
embedd = discord.Embed(description=f"Usage: \`\`\`^embed [message]\`\`\`",
color=0x2ae1e9
)
await ctx.message.reply(embed=embedd)
elif titlee is None:
embeddd = discord.Embed(description=f'{content}', color=0x2ae1e9)
await ctx.message.delete()
await ctx.send(embed=embeddd)
pass
elif footerr is None:
e = discord.Embed(title=f"{titlee}", description=f"{content}", color=0x2ae1e9)
await ctx.message.delete()
await ctx.send(embed=e)
else:
embed = discord.Embed(title=f"{titlee}", description=f"{content}", color=0x2ae1e9)
embed.set_footer(text=f"{footerr}")
await ctx.send(embed=embed)
await ctx.message.delete()``` anyone have any ideas on how i can fix?
what is the erorr
no error code, but what i want is to do ^announce "desc" "title" "footer"
but if i did ^announce "desc" "title" "footer" then it literally just sends an embed with the description being '"desc" "title" "footer"'
i hope u understand that 😭
@novel rampart is that good help or
ill send visual
you cannot use * for the first argument if there are multiple arguments
ill try
works, tyvm

its an image screenshot effect lmao
ofc-
intersting-
very
How do I send messages in a server while using the message param
bruh
message.channel.send()
gracias
The TextChannel or Thread that the message was sent from. Could be a DMChannel or GroupChannel if it’s a private message.
:) there it is
!d datetime.datetime.utcnow
classmethod datetime.utcnow()```
Return the current UTC date and time, with [`tzinfo`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime.tzinfo "datetime.datetime.tzinfo") `None`.
This is like [`now()`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime.now "datetime.datetime.now"), but returns the current UTC date and time, as a naive [`datetime`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime "datetime.datetime") object. An aware current UTC datetime can be obtained by calling `datetime.now(timezone.utc)`. See also [`now()`](https://docs.python.org/3.10/library/datetime.html#datetime.datetime.now "datetime.datetime.now").
Warning
Because naive `datetime` objects are treated by many `datetime` methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing the current time in UTC is by calling `datetime.now(timezone.utc)`.
how do i make bot to wait until i response?
code?
Then why error?
i mean, i'd first start by casting 891168982965563482 as an int. do int(891168982965563482) to ensure it is an int
Hey, I wanna self deploy @unkempt canyon bot.
I just wanted to know where to store
Bot token ik I have to place token in .env but where.
I'm a noob in discord py
How's to
its already int if there is no ' '
oh try to make variable list
doesnt matter. do it anyway. somewhere he's casting a string where an int needs to be
list = [827123687055949824,853535211581341737,738609666505834517,826823454081941545,886120777630486538,799975931224784897,853306806116548609,757832621769097226]
is it working?
where did you want to deplot?
try make the list variable
if ctx.author.id in list:
is this in a cog?
i think we dont need self in non-cogs
async def vcchess(ctx):
authorids = [827123687055949824,853535211581341737,738609666505834517,826823454081941545,886120777630486538,799975931224784897,853306806116548609,757832621769097226]
if ctx.author.id in authorids:
await ctx.message.delete()
authorchannelid = ctx.author.voice.channel.id
link = await togetherControl.create_link(authorchannelid, 'chess')
print(link)
```?
nvm
i assume that since @slate swan didnt respond so fast, it must've worked
Coz everything else he replies super fast
no coz you need to fix discord indents
fix the indents and you're fine
4 spaces is 1 indent.
lemme send screencap
Heroku
channel = get(guild.text_channels, name='get-logs')
print(channel.id)
if channel is None:
channel = await guild.create_text_channel('get-logs')
print(channel.id)
why its not creating log
yes lonleyGirl is right, just do bot.run('your token')
did some testing @slate swan
async def vcchess(ctx):
authorids = [827123687055949824,853535211581341737,738609666505834517,
826823454081941545,886120777630486538,799975931224784897,
853306806116548609,757832621769097226]
if ctx.author.id in authorids:
await ctx.message.delete()
authorchannelid = ctx.author.voice.channel.id
link = await togetherControl.create_link(authorchannelid, 'chess')
print(link)
``` Fix indents.
Okie
the first print statement won’t be able to access the channel id if channel is None, that’s why it’s throwing the error
you’d have to only print the id if channel is not none
or just get rid of that print statement
if channel==None
I am saying fix indents coz you wont fix them when you copy and paste. the issue was your authorchannelid.
author = ctx.author
guild = ctx.guild
channel = get(guild.text_channels, name='get-logs')
print(guild.channel.id)
if channel is None:
channel = await guild.create_text_channel('get-logs')
print(guild.channel.id)```
you want to use is for comparisons with None
yeah, but before you create a channel, you’re trying to access channel.id in your print statement, but channel doesn’t exist yet— that’s why you’re getting that error
you can actually change this to if not channel instead.
now run it.
Then your issue is link
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
authorchannelid = ctx.author.voice.channel.id requires the author to be in a voice channel.
If they aren't you'll get an error.
await ctx.send(authorchannelid) I use to confirm this.
she’s making a selfbot, we can’t help with that
idk what a selfbot is
it’s where you use a user token to run your code— basically you automate your own account
it’s against discord’s terms of service
oh
idk what that is
so the code itself works, it's just @slate swan is breaking some laws or something? 🤔
Well. I know the code works
It's just @slate swan who is failing to get it to work
¯_(ツ)_/¯
idk if the code works (haven’t tested it) but shes using it in a way that breaches discord’s ToS and as per this server’s rules we cannot provide help with that
I tested it. the code works. I cant test link tho but i assume that works
that’s not the issue— the issue is that we cannot discuss this here
What?
How is a module a self bot?
every time i try to use the ban command on my bot the missing permission error pops up even though i have the required permissions to call the command ....
any1 have any idea y?
does the bot have perms
maybe the user your trying to ban is above the bot in terms of perms
nope
why am i getting this error```py
Ignoring exception in slash command 'rolemenu':
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/ext/commands/slash_core.py", line 239, in invoke
await self(inter, **inter.options)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/ext/commands/base_core.py", line 135, in call
return await self.callback(self.cog, interaction, *args, **kwargs) # type: ignore
File "/home/runner/BetaBot/cogs/buttons.py", line 153, in rolemenu
view=View(placeholder, min_values, max_values, options)
File "/home/runner/BetaBot/cogs/buttons.py", line 48, in init
self.add_item(MyMenu(placeholder, min_vals, max_values, options))
File "/home/runner/BetaBot/cogs/buttons.py", line 39, in init
self.fill_options()
File "/home/runner/BetaBot/cogs/buttons.py", line 43, in fill_options
self.add_option(label="something")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/ui/select.py", line 228, in add_option
self.append_option(option)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/ui/select.py", line 245, in append_option
raise ValueError('maximum number of options already provided')
ValueError: maximum number of options already provided
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/ext/commands/bot.py", line 1296, in process_application_commands
await app_command.invoke(interaction)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/ext/commands/slash_core.py", line 248, in invoke
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: maximum number of options already provided
maximum options?
so i have a command which sends the user's avatar, and it used to work fine a while back, but now its broken. this is my code
@commands.command()
async def avatar(self, ctx, *, member : discord.Member):
useravaurl = member.avatar.url
await ctx.send(useravaurl)```
And this is the error:
```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute
'url'```
hm, by the looks of it, it looks like you have reached the maximum amount of options in a selection ui thingy, i don't have experience in disnake tho
@commands.command()
async def avatar(self, ctx, member : discord.Member):
useravaurl = member.avatar.url
await ctx.send(useravaurl)
try removing the * in *, member : discord.Member)
oh its dpy 2.0 here at least
ok, i'll try that
^
it still gives me the same error
class MyMenu(discord.ui.Select):
def __init__(self, placeholder, min_values, max_values, options):
super().__init__(placeholder=placeholder, min_values=min_values, max_values=max_values)
self.options = options
self.fill_options()
def fill_options(self):
for option in self.options:
self.add_option()
class View(discord.ui.View):
def __init__(self, placeholder, min_vals, max_values, options):
super().__init__()
self.add_item(MyMenu(placeholder, min_vals, max_values, options))
``````py
async def command(self, inter):
placeholder="something"
max_values=2
min_values=1
options = [discord.SelectOption(label="something")]
view=View(placeholder, min_values, max_values, options)
await inter.response.send_message(".", view=view)
```I'm trying to add an option to a menu and send it but it doesn't seem to work. can someon help me
are u using 2.0 or 1.7?
let me check one sec
Missing permissions error is raised because the person calling the commands doesnt have the permission ri8
wait how do i check the module version? i forgot the command
pip freeze
or pip show discord.py
1.6.0
bruh
alright i get it now
why were u using .url then?
interactions
and some other stuff
can someone help me add options to a select menu ;-;
ive been trying for so long
how to update discord.py
install danny's master version
every time i try to use the ban command on my bot the missing permission error pops up even though i have the required permissions to call the command ....
any1 have any idea y?
What's a danny
Bot might need perms
bcoz the bot'role is down the members u know hierarchy
yes
um
@trail breach
ok
my Bot's in 86 servers getting verified
woah 86?!
this is the simple hierarchy
Then perhaps you need to make sure your bot is only banning from the server the command is run on
guild.ban?
idk maybe. lemme consult the documentation
await member.guild.ban(reason = reason)
Sure try that
Put the account in both servers
yeah to check ok
alternatively, you could do
guild = ctx.guild
guild.ban(member, reason)?
```https://discordpy.readthedocs.io/en/master/api.html?highlight=ban#discord.Guild.ban
lemme try once
in the second server my bot doesnt have perms
the creator of dpy
could u test ban me ? invite me bro maybe i can help u
with the code
u know thats SUS ri8
bro i sec
Awesome. code and error?
can someone help me add options
code
lol
!paste
It's fine. Invite him lol. as long as your commands have commands.is_owner() you will be fine
bro see
how did you make your help come up like that?
see my bot is in verification process
@trail breach
dont be offended....but sorry
i did not get u
its ohk i am telling u to test ban me
It is not working from the new discord update
i have an alt for the job
When you type $help your response is like that but mine appears differently lol
show me
embeds
it is embed
yes embeds XD
BRUH
uhh. your prefix is set to mu with a space after mu?
Yes but how did you edit it?
bro its a magic when u can edit i have 2 employees under me
it is not able to join the voice channel that I am in
how you get the pfp cuz i want it but it must be a var
!custom-help
Custom help commands in discord.py
To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000
which pfp
like it shud be of the peerson i ping in my command
Thank you for actually answering my question.
bots pfp
my personal editor
ohk
u know maybe i can share u the code
nice
nah
no no
ill make myself sense of pride
ohk its fine
when u learn things and find bugs it motivates u to solve the problem @trail breach
oh so thats how you're using stats? XD
yes
Lemme show you my stats
whai i just copied the dyno's serverinfo
still the error even after ctx.guild.ban
theres a dpy 3.9.6?
@bot.command()
@commands.has_permissions(ban_members = True)
async def ban(ctx,member:discord.Member,*,reason = "No reason"):
await ctx.send(f"{member.name} has been banned {reason}\namen")
guild = ctx.guild
await guild.ban(member, reason = reason)
# await asyncio.sleep(int(time))
# await member.unban()```
😄
do u need help with ban?
I have a working ban code
me too
remove member from brackets and meber.ban
@high pollen No spoonfeeding please
i have ban kick mute slowmode every single moderation command cod
ok
Why?
just help me fix mine 🙂
yes everyone has it
but i wont give it >:))
me too
same lol
@trail breach Is there an error..
again missing perms
do u have perms?
is it becuz in the 2nd server my bot doesnt have any powers
check ur dms
i have perms
try making a role and make it have admin and then it to urself
@slate swan stop spoonfeeding
guys, i want to download an image on my computer using the link of the image from discord, how do i do that?
use await member.ban(reason = reason)
wdym? hes doing it the right way..
i want it to be only on 1 server
@commands.command(help='[Bans the mentioned user.]')
@commands.has_any_role('bot','Bot','Owner')
async def ban(self, ctx, member : discord.Member, *, reason = None):
if reason == None:
reason = "No reason given."
guild = ctx.guild
await guild.ban(member, reason=reason)
``` is my ban code
@drifting arrow no spoonfeeding pls
it was made a month ago before I learnt about permissions
ohk
not spoon feeding
then what?
They've been discussing this for a while. trying different things.
I thought I'd share my version
also this wrong.
Not much difference between what I just did and simply saying use this
@trail breach
How so?
no it isnt?
i have done that
use if member.top_role < ctx.author.top_role: to check if bot is higher than the user
or i can ban head mod
or admin
thats optional?
dmsbro i said him to invite me to his server and he is currently testing the bot on me
ye but better
kk
ur dev in mordex literally
yeah, but it isnt wrong..
im alpha in this nex 2 are for bot and the rest for peasants
it is not wrong but anyone with ban members perms can ban anyone
wot
also this wrong.
?? i did not get you
Also I need help with my bot
Code 🆙
It is too big to paste here
hey guys
It returns voice as None Always
can someone help me with dpy 2
hey
How to localize discord bot using gettext? (Users can select bot's language on their servers)
I updated my code to reflect what was 'wrong'
@commands.command(help='[Bans the mentioned user.]')
@commands.has_permissions(ban=True)
async def ban(self, ctx, member : discord.Member, *, reason = None):
if reason == None:
reason = "No reason given."
if ctx.author.top_role > member.top_role:
guild = ctx.guild
await guild.ban(member, reason=reason)
elif ctx.author.top_role < member.top_role:
await ctx.send(f"I'm sorry {ctx.author.mention}, but I cannot ban someone who is better than you.")
elif ctx.author.top_role == member.top_role:
await ctx.send(f"I'm sorry {ctx.author.mention}, your roles match and according to article 32, subsection 193, paragraph 3, dotpoint 8, I can't ban him")
else:
await ctx.send("Can't ban. Soz bro.")
you satisfied?
ok
ok
@drifting arrow help
The code I sent should work.
ok
I'm referring to when ya'll were like 'dont spoonfeed' after discussing for like an hour.
that original code block would only work if you didnt specify a reason
or did I fix it? idk
idc. moving on.
I hate code that requires me to test on people xD
Does anyone know dpy2.0
how can i change the color of text when i print
My friends have started to ignore me coz of the spam
RIP
https://discordpy.readthedocs.io/en/master/ ? i use this to reference everything
hmmmm
i need help with adding options to a menu
but i cant seem to understand
adding options on command*
too many classes and stuff, i dont get it
YES```py
class Dropdown(discord.ui.Select):
def init(self):
super().init(
custom_id="RoleMenu",
placeholder="Select Role(s)",
min_values=0,
max_values=len(2),
options=[
discord.SelectOption(label="Hello"),
discord.SelectOption(label="Hi")])
thats my class
I've never used those new features
ah
so I wouldn't have a clue xD
ALTHOUGH with that being said. I might do a tic-tac-toe game using those buttons..
well when we add to many buttons it looks like shit literally
¯_(ツ)_/¯
tbh this didnt help but
im trying to change the color for each leter
what tell me
Meaning..?
wanna make one letter red, the other black, the one after blue
Use an extension I guess?
you cant, colorama only works for console
discord doesn't support anything like that
thats what i wanna use it for
and its not working
bro lol u dev in Mordex
i need to add options to a menu
and also determine its placeholder, max and min values based on the options the user types
means a embed or buttons
select menu
can i change the bot's profile color?
The banner? If so, you can't. Only the bot's pfp & about me.
try to look at the examples maybe it'll help
k
couldnt find any good examples to add options
hm
or linkslike mine
?
bymistake
then wot this
bro i did not understand it at first
'_'
this??
bro what do you mean
that menu
then u want it to be unique
sorry but now i was just saying an option
he said he wants a select men not a help command
i was talking about discord.ui.Select
i delete
what lib?
ik but menu for discord bot right so
disnake but this stuff is completely dpy 2.0
i realized that view.children[0].add_option() adds an option
is there a better way to execute this?
install danny's master version of the repo from github
ohk
i realized that view.children[0].add_option() adds an option
is there a better way to execute this?
uhh
and also, how do i add the placeholder, min and max values on command
whats wrong with it?
i still didnt understand the thing :/
same
not sure
@client.command()
async def Pball(ctx , question):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
eightball = ['Yes','No','Probably','Of Course','Of Course No','From my point of view , yes','100% No','I Donnow','Ask Me Later','Im Busy , Sorry ','Im sure yes','I Guess No']
embedVar = discord.Embed(title=f"✦Peachy Bot✦\n Question By {username} ",color=0x00ff00)
embedVar.add_field(name="Answer By Peachy Bot :", value=(f'{question}\n=> {random.choice(eightball)} .'),inline=False)
await message.channel.send(embed=embedVar)
return
Ignoring exception in command Pball:
Traceback (most recent call last):
File "C:\Users\Modarresan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Modarresan\Desktop\Peachy Bot\Peachy.py", line 89, in Pball
username = str(message.author).split('#')[0]
NameError: name 'message' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Modarresan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Modarresan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Modarresan\AppData\Local\Programs\Python\Python39\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: NameError: name 'message' is not defined
uhh
message.author is wrong. there's no message. instead change that entire first line to be username = ctx.author.name
and using dpy returns string so no need to cast as a string
so user_message = str(message.content) can be change to user_message = ctx.content
yes you are right
- Use
ctxinstead ofmessage. - Channel names & message contents are already strings why are you recasting them as strings?
you trying to get a count of members with x role?
property members: List[Member]```
Returns all the members with this role.
This @slate swan returns all the members with the role
does anyone know how to create a customized menu on command, i.e. a menu with the text the user sends as the placeholder and variable max and min values?
Meaning? An error?
oof
run the command ig
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.commands' raised an error: AttributeError: type object 'commands' has no attribute 'command'
output?
uh...
maybe dont name ur cog like that
maybe variable hierachy or something
alright
wait
show ur cog
o ok
?
o i meant the
em.add_field(name="Users", value=role.members)
``` and change this back to ```py
role: disnake.Role
huh
That means no one has the role
use len()

