#discord-bots
1 messages · Page 540 of 1
i mean you could still try
and this is my first time
try this ```py
@client.event
async def on_message(message):
print(message.channel.name)
await client.process_commands(message)
Why would that change anything
Do your bot comes online when you run the script?
yeah
and it prints the first event
And in addition to that, client doesn't have process_commands @slate swan
Only Bot has
and did you send any messages to channels that your bot can see after that
I sent loads of messages
and nothing printed in the output
Can the bot see the channel
how was i suppose to know i dont use discord.Client
let me see
Your bot has view_channel permission in that channel?
If the bot can't see the channel it's normal nothing gets printed
And you should use Bot instead of Client if you plan on adding commands
yes
does your bot have view_channels??
oh nvm you said yes LOL
I mean, when i added the bot
theres no role
That the bot has.
Idk why
Just make sure the bot can see the channel you're sending messages in
^
and that doesn’t help?
@bot.event
async def on_message(message):
await message.channel.send('Hello')
I changed the event to this
and still doesnt work
Just one question, when you have a bot doesnt it have a role that you cant delete?
Have you changed your variable names too?
And the bot has to have it.
Not always
mhm
@bot.event
async def on_ready():
print('Bot Is Running as {0.user}'.format(client))
@bot.event
async def on_message(message):
await message.channel.send('Hello')
client.run(TOKEN)```
If you invited the bot without any permissions no role is being created
Please take a closer look at
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html
consider using commands.Bot
You will see that you shouldn't use Client
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
And you need to use bot.run and not client.run since you changed the variable name now
from discord.ext import commands
import random
TOKEN = ''
bot = discord.Client()
@bot.command()
async def on_ready():
print('Bot Is Running as {0.user}'.format(client))
@bot.command()
async def on_message(message):
await message.channel.send('Hello')
bot.run(TOKEN)```
**This is my code now**
I did the command thing as you guys said
.
commands dont work with discord client...
use commands.Bot instead
and why is on_message a command its an event
your formatting client with a bot definition
please learn basic python and basic dpy
I came here for help. I couldnt find anything on the internet so I came to the py community
Sorry for not knowing the basics
dpy isnt a "starter" or "basic" lib
Everything's there:
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html
There are even examples
Take the time to look at the page
And you should learn Python more than just the basics
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Could remove the non needed import
Well, it's not used anywhere
Not in that code
ik
Is javascript discord easier than discord.py?
preferences
Js isn't necessarily hard, but for making a discord bot it's somewhat harder than in dpy (provided that you don't just plan on making the bot online and just that which can also be a pretty challenging task for beginners), python is more friendly
Ok so I'm trying to rising a MissingRole error but when the bot do it the error handler get a NoneType object instead of a MissingRole object, how to solve this?
code's here:
role: Role = db.field("SELECT WRRoleID FROM guilds WHERE GuildID IS ?", ctx.guild_id)
if not role:
await ctx.send("Non è stato ancora impostato un ruolo per questi comandi")
breakpoint()
author: Member = ctx.author
if role.name not in author.roles:
raise MissingRole(role)
@bot.command()
async def vkick(ctx, user : discord.Member):
await user.move_to(None)
await ctx.send(f"He expulsado a {user.mention} del canal de voz!")``` How i can make the user mention to pingt the person who i kicked¿
await ctx.send(ctx.author.mention)
you can look things up lol but thats what i found
@slim whale
tnxxx
no prob
No one?
i dont know how to fix that let me try and help @placid skiff
lets see if google has a fix
i'm actually searching it xD
async def say_error(ctx, error):
Missingrole = get(guild.roles, id=730356075689410570)
if isinstance(error, commands.MissingRole(missing_role)):
await ctx.send(f'`You dont have {Missingrole} role..')```
async def say_error(ctx, error):
if isinstance(error, commands.MissingRole):
if error.missing_role.id == 730356075689410570:
await ctx.send(f'`You dont have {error.missing_role} role..')
else:
await ctx.send("You are missing some other role")
else:
raise error # if we can't handle the error, bubble it back up```
take a look at this one @placid skiff
!eval {ctx.command}
@stoic galleon :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'ctx' is not defined
to use that i have to use checks, but i can't use them 'cuz i don't know the role missing until the command is runned
so I have to raise the MissingError object manually
Hi i'm trying to make a command with pages but it's hard
try to use discord.ext.menus: https://github.com/Rapptz/discord-ext-menus
Hi, anyone knows how to do this? Have seen it only few times recently and I'd like to use it in my bots as well.
https://i.imgur.com/YTQprjf.png
I was actually wondering this too
Hopefully someone will be able to answer us!
I think there's a page on discord "documentation"
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...
How do people do it in their about me's though
Go to dev-portal, your bot, and then the Description is the about me
Settings => user profile
I mean the time thing in the about me
Thanks! Could u show me some example of how it should be implemented? I'm kinda confused of it and I'm not able to find anything except the docs.
Didn't even know that this is possible
from datetime import datetime
dt = datetime.now()
await ctx.send(discord.utils.format_dt(dt, 'R'))
Using a timestamp
Look at the admin Xithruis
Alr
Wait, that's disnake not discord.py
The implementation should be same, nvm
e.g:
<t:1634428410:R>
<t:1634428410:R>
Ah mb, just change disnake with discord
There I fixed it
NameError: name 'FFmpegPCMAudio' is not defined
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord.utils' has no attribute 'format_dt'
Version of dpy?
I'm receiving this error with that
shit
woops
That's one big queue
How can i get a members top role position?
You're not importing it
!d discord.Member.top_role
property top_role: Role```
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
I'll just make it by <t:1634428410:R>, that's easier
so do Member.top_role.position()?
Yeah you can do that
No, you need a Member instance, top_role is a property of Member
okay so i can do
l = ctx.author.top_role
p = l.position()
Yeah
okay thanks for your help
Yw
Heyyyy, I've got a quick problem, and was wondering if you guys might know what's up.
So, I'm sending messages with await ctx.send("Message")
I'm storing the message object in a variable using sent_message = await ctx.send("Message")
However, when I later go to lookup for any new reactions on that message object, it returns an empty list, even though reactions exist on the message. Am I missing something?
You stored it at that moment, it doesn't get updated so it's the reactions at the moment it got sent
So I need to fetch it again?
Yeah, depending on what your trying to do
I'm just looking to see if there are any new reactions. So I guess that means I need to store the message ID
@client.command()
async def delete(ctx):
db = await aiosqlite.connect('database.db')
cursor = await db.execute("SELECT users FROM currency WHERE users=?", (ctx.author.id,))
rows = await cursor.fetchone()
if rows is None:
embed = discord.Embed(title="Delete",
description=f"You're not registered!",
color=discord.Color.orange())
await ctx.reply(embed=embed)
else:
def check (message):
return message.channel == ctx.channel and message.author == ctx.author
embed = discord.Embed(title="Delete",
description=f"Reply with `yes` if you **WOULD** like to delete your profile. Reply with `no` if you would **NOT** like to delete your profile.",
color=discord.Color.orange())
await ctx.reply(embed=embed)
try:
c = await client.wait_for('message', timeout=60.0, check=check)
if c.content.lower() == "yes":
cursor = await db.execute('DELETE FROM currency WHERE users=?', (ctx.author.id,))
cursor = await db.execute('DELETE FROM inventory WHERE users=?', (ctx.author.id,))
cursor = await db.execute('DELETE FROM pets WHERE users=?', (ctx.author.id,))
rows = await cursor.fetchall()
cursor = await db.execute('SELECT * FROM currency')
rows = await cursor.fetchall()
await db.commit()
await db.close()
embed = discord.Embed(title="Delete",
description=f"You've deleted your profile!",
color=discord.Color.orange())
await ctx.reply(embed=embed)
return``` How can I reply to the `yes` message the user sends rather than the command?
For the second ctx.reply(embed=embed) (near the very bottom)
Yeah. But don't fetch too frequently, like once every 5 or 10 seconds at for a single message
If you just want to wait for one reaction to be added, there's a better way. Wait_for
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
Yeah, I had seen something about that in docs, thanks for bringing it up again!
No problem!
That's odd it should've been updated, at least if I remember the code correctly, as discord.py internally inside of state receive the reactions via the gateway, then they call the _update method of the Message which refreshes all of its attributes
That's what I thought it would do
Hmmm i thought otherwise
Yep, they do it right here in state
I'm not sure why it didn't update the attributes although
I saw a really old GitHub issue on this, not sure if it is still valid though: https://github.com/Rapptz/discord.py/issues/861
m = send(...)
wouldnt that store it as a local variable at that point time?
I don't think this valid anymore, as either way when the bot sends a message it will dispatch through the gateway, then it will be sent to the parsers and cached
Yes, that's how python works
yeah thought so too. would be kinda impossible to update the local variables of a function 🤔
it updates the ones in the internal cache but thats it
Hi

Ah yes I just realized that lmao
I was thinking about a case in my wrapper where I had to do that
but I didn't retrieve from the cache after that
im so spoiled with ctx that I didn't think of that
Only top.gg and the source code in GitHub
Yes
I can make it a website
Pain
I love that someone made this
Its very limited
Nah
Do you like it?
Thats an disadvantage
its so very obscure
And I'd need to port forward, get a domain and etc . No thanks
ngrok it
Not very hard, that's what I did for my old http server impl for interactions
although the url can be very dodgy
I made the module 
sweet!
I didnt work on it for a while
I should add more features
Like different styles etc
Oh it's yours lol
I gtg now byeee
Yea

Ok cyaaa
adios
from __future__ import annotations
from typing import Dict, Type, Tuple, TYPE_CHECKING, ClassVar
from .command import Command
if TYPE_CHECKING:
from ..bot import Bot
__all__ = ("Plugin",)
class PluginMeta(type):
__commands__: Dict[str, Command]
def __new__(
cls: Type[PluginMeta], name: str, bases: Tuple[Type], attrs: Dict
) -> PluginMeta:
commands: Dict[str, Command] = {}
for attr, value in attrs.copy().items():
if isinstance(value, Command):
commands[attr] = value
attrs["__commands__"] = commands
return super().__new__(cls, name, bases, attrs)
class Plugin(metaclass=PluginMeta):
__commands__: ClassVar[Dict[str, Command]]
def _attach_commands(self, bot: Bot):
for name, command in self.__commands__.items():
command.parent = self
bot.commands[name] = command
``` This is currently how I'm handling "Cogs" in my discord API wrapper, I'm marking commands via a decorator and the metaclass checks for that which is how its appending. Is there some other metaclass trickery I can do here
?
we are not here to code for ppl we help
will you help me?
sure
😄
but i wont code everything
ill dm you my private script
?
!d discord.Intents
class discord.Intents(**kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
New in version 1.5...
looking for a team dm me
For what
How can i add startup message for my bot
you could do it on on_ready
but that's called multiple times as you can get randomly disconnected from the server
if you want that you can do that
yo does anyone know how to get a list of all channels in a server with the id?
get the guild object using get_guild, then use the text_channel attribute of that object
so bot.get_guild?
yeah
can i just transfer my code to a maintened version of discord.py?
cuz for some of them it doesnt work
any suggestions?
does the get_guild take any arguement?
command?
the guild id
!d discord.Client.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
Any specific subject/area?
uh examples?
i give the id right?
maybe
yep it is asking for id
Rythm is a music bot, mee6 is a leveling bot, Carl is a moderation bot stuff like that
all exept music
the id
mainly moderation and some lvling might even add 1 game
So general purpose. I'm not interested
in string?
ids are always ints
oh ok
kk 😭
What is meant by 'Member' object is not subscriptable? I have a dictionary that includes a Member (ctx.author, to be exact) object as a value, which seems to be causing the error.
Hey general questions about fonts. Does anyone know when it comes to embed messages how we can highlight like this?
you are doing member_obj[stuff]
<t:TIMESTAMP:FORMATLETTER:>
I'm doing active_player['User'] which is member_obj as the value.
<t:1634453749:F> like so
active_player is a Member obj?
wait wot Robin, how exactly do you apply this?
TIMESTAMP - the current unix epoch time
format letter - R, F, f, etc
OOH
you can set that int he embeds
it doesn’t have to to be the current one
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Thank you I was actually trying to find the source
Oh wait I think I just solved the problem.
thank you
<t:1634453749:R>
useful for like giveaways and stuff since it's live
or for reminders
ye
thank you again robin
no prob
yo does anyone know why my bot.get_guild returns None?
because the guild is not cached yet
wdym by not cached?
What would i put beside app = Flask(name)
in name would i put in the bot name or what?
How to send message in a server which is view only one person ?
Discord.py uses something known as a cache. It's basically a way Discord.py and other wrappers use to store data about guilds, users, and other useful information. This cache is used to avoid calling the Discord API a lot, so that instead of calling that, you can just access the cached element or whatever Discord.py has stored for that object.
What they mean is that the guild is not in this special list, and as such will return None, note that get_* methods generally attempt getting data from cache first, while fetch_* methods actually call the API.
So yeah, the point is, try using Bot.fetch_guild, see if that works.
"which is view only one person" - how so? do you want the message to only be viewed by that person or something?
yas
empheral messages
There are two ways to do this: the first one is using ephemeral messages (which are basically the messages Clyde sends -- can only be viewed by you) as someone mentioned, although for those, you would have to use something like a slash command (or some sort of interaction) and respond to that interaction with that ephemeral message.
The simplest way to do this without interactions is simply just DMing the user.
Is it ok if I name my file Discord.py and not discord.py?
Apparently looks like it is, although wouldn't really recommend it, but you can do it.
Yea
oh ok
naming your bot file as discord.py is no good
🔪 what if you do import discord in some other file in the same directory , it will import your bot file if am not wrong
^
But they are naming it Discord.py, which I don't really think would create a problem
yeah
.help
Prefix is !
How would I make a timestamp be right now? Like one of these: <t:1624385691:R> (<t:1624385691:R>)
for the current time?
Yes, please.
datetime.datetime.now().timestamp()
¯_(ツ)_/¯
it returns a float , convert it to an int
Hmmm, I see, thanks!
How can I get guild member number or bot number?
How can I check it
and send the value?
Are cogs needed on bot?
Cogs makes much easier to make bots
If you use cogs, It's easy to make help commands and more
when a user join/moves to another vc can i make the bot to move to that same vc using on_voice_state_update????
do you mean number of members and bots in a guild?
YES
!d discord.Guild.member_count
property member_count: int```
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be specified.
omg
and you can interate thru guild.members which return a list of members
thanks
!d discord.Member.bot
property bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.bot "discord.User.bot")
use this to check if a member is bot
Okie~~ thanks
you can use after.channel to get the channel in which the user is now
Than Is my code right?
@bot.command()
async def member(ctx):
member=member_count
await ctx.send(member)
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/runner/owner.py", line 668, in on_voice_state_update
channel = after.voice.channel
AttributeError: 'VoiceState' object has no attribute 'voice'
Ignoring exception in on_voice_state_update
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/runner/owner.py", line 668, in on_voice_state_update
channel = after.voice.channel
AttributeError: 'VoiceState' object has no attribute 'voice'
Ignoring exception in on_voice_state_update
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/runner/Trust-Worthy-Runtime-Bot-2/owner.py", line 668, in on_voice_state_update
channel = after.voice.channel
AttributeError: 'VoiceState' object has no attribute 'voice'
Ignoring exception in on_voice_state_update
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/runner/owner.py", line 668, in on_voice_state_update
channel = after.voice.channel
AttributeError: 'VoiceState' object has no attribute 'voice'
yeah
What is member_count?
sorry , pls read the edit , its after.channel
it must be ctx.guild.member_count..
Ohhhh
its a property of discord.Guild
And where did you define it in your code?

Traceback (most recent call last):
File "/home/runner/Trust-Worthy-Runtime-Bot-2/owner.py", line 670, in on_voice_state_update
await channel.connect()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 1669, in connect
raise ClientException('Already connected to a voice channel.')
discord.errors.ClientException: Already connected to a voice channel.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/runner/Trust-Worthy-Runtime-Bot-2/owner.py", line 672, in on_voice_state_update
await after.guild.voice_client.move_to(channel)
AttributeError: 'VoiceState' object has no attribute 'guild'
Ignoring exception in on_voice_state_update
Traceback (most recent call last):
File "/home/runner/owner.py", line 670, in on_voice_state_update
await channel.connect()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 1669, in connect
raise ClientException('Already connected to a voice channel.')
discord.errors.ClientException: Already connected to a voice channel.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/runner/Trust-Worthy-Runtime-Bot-2/owner.py", line 672, in on_voice_state_update
await after.guild.voice_client.move_to(channel)
AttributeError: 'VoiceState' object has no attribute 'guild'
Ignoring exception in on_voice_state_update
Traceback (most recent call last):
File "/home/runner/Trust-Worthy-Runtime-Bot-2/owner.py", line 670, in on_voice_state_update
await channel.connect()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 1669, in connect
raise ClientException('Already connected to a voice channel.')
discord.errors.ClientException: Already connected to a voice channel.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/runner//owner.py", line 672, in on_voice_state_update
await after.guild.voice_client.move_to(channel)
AttributeError: 'VoiceState' object has no attribute 'guild'
@slate swan got this
await after.guild.voice_client.move_to(channel)
after is a voicestate object which does not have a guild attribute
voice_state_update has a member argument , use it
!d discord.Member.guild
The guild that the member belongs to.
for?
Traceback (most recent call last):
File "/home/runner/owner.py", line 670, in on_voice_state_update
await channel.connect()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 1669, in connect
raise ClientException('Already connected to a voice channel.')
discord.errors.ClientException: Already connected to a voice channel.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/runner/Trust-Worthy-Runtime-Bot-2/owner.py", line 672, in on_voice_state_update
await after.voice_client.move_to(channel)
AttributeError: 'VoiceState' object has no attribute 'voice_client'
Ignoring exception in on_voice_state_update
Traceback (most recent call last):
File "/home/runner/owner.py", line 670, in on_voice_state_update
await channel.connect()
AttributeError: 'NoneType' object has no attribute 'connect'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/runner/owner.py", line 672, in on_voice_state_update
await after.voice_client.move_to(channel)
AttributeError: 'VoiceState' object has no attribute 'voice_client'
Ignoring exception in on_voice_state_update
Traceback (most recent call last):
File "/home/runner/owner.py", line 670, in on_voice_state_update
await channel.connect()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 1669, in connect
raise ClientException('Already connected to a voice channel.')
discord.errors.ClientException: Already connected to a voice channel.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/runner/Trust-Worthy-Runtime-Bot-2/owner.py", line 672, in on_voice_state_update
await after.voice_client.move_to(channel)
AttributeError: 'VoiceState' object has no attribute 'voice_client'
got this again
where did you get this code?
i made this now
@commands.Cog.listener()
async def on_voice_state_update(self,member, before, after):
channel = after.channel
try:
await channel.connect()
except:
await after.voice_client.move_to(channel)
well you should look after the docs while doing so
i did
hi, so self.bot = asyncio.run(__class.context.bot.get_context(self.message)) so currently this cant be executed with a running event loop. Should I just use asyncio.create_task() or is there something better?
why not loop.run_until_complete idk
I don't know much but there is from discord.ext import tasks
Or that, yea
I don't know if it is right
oh wait, i forgot that it exists
kylee and hunter meets!!

Calm down 😐
LOL
self.bot = __class.context.bot.loop.run_until_complete(__class.context.bot.get_context(self.message)) ew so long
🤷♂️just break it into parts then. Or just make a property
||I gotta go||
But why u setting the bot variable to the context
Cya!
so I can call callback.bot instead of callback.__class.context.bot
its not a cog btw
how do i make wall text discord.py
if user_message.lower() == '*specs':
embed = discord.Embed(title="Sunflower Duck's PC specs", url="https://www.youtube.com/watch?v=dQw4w9WgXcQ",
description="SSD: M.2 1000GB Hard Drive",
color=0xFF5733)
ok... so i wanna add other component lists in desc
Can u please use commands
!d discord.ext.commands.Command
class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the decorator or functional interface.
? wdym
C:\Users\drago\anaconda3\envs\itsuki-bot\lib\asyncio\base_events.py:1860: RuntimeWarning: coroutine 'BotBase.get_context' was never awaited
handle = None # Needed to break cycles when an exception occurs.
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
ERROR:asyncio:Task exception was never retrieved
future: <Task finished name='Task-35' coro=<Paginate.listen() done, defined at C:\Users\drago\PycharmProjects\itsuki-bot\ext\pagination.py:71> exception=RuntimeError('This event loop is already running')>
Traceback (most recent call last):
File "C:\Users\drago\PycharmProjects\itsuki-bot\ext\pagination.py", line 82, in listen
elif check(self.__callback(self, r, u)): # pass the PaginationCallback to `check` parameter
File "C:\Users\drago\PycharmProjects\itsuki-bot\ext\pagination.py", line 21, in __init__
self.bot = __class.context.bot.loop.run_until_complete(__class.context.bot.get_context(self.message))
File "C:\Users\drago\anaconda3\envs\itsuki-bot\lib\asyncio\base_events.py", line 592, in run_until_complete
self._check_running()
File "C:\Users\drago\anaconda3\envs\itsuki-bot\lib\asyncio\base_events.py", line 552, in _check_running
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
```umm
Just sent the docs above
Then just do get_running_loop or something
ERROR:asyncio:Task exception was never retrieved
future: <Task finished name='Task-35' coro=<Paginate.listen() done, defined at C:\Users\drago\PycharmProjects\itsuki-bot\ext\pagination.py:72> exception=RuntimeError('This event loop is already running')>
Traceback (most recent call last):
File "C:\Users\drago\PycharmProjects\itsuki-bot\ext\pagination.py", line 83, in listen
elif check(self.__callback(self, r, u)): # pass the PaginationCallback to `check` parameter
File "C:\Users\drago\PycharmProjects\itsuki-bot\ext\pagination.py", line 22, in __init__
self.bot = self.loop.run_until_complete(__class.context.bot.get_context(self.message))
File "C:\Users\drago\anaconda3\envs\itsuki-bot\lib\asyncio\base_events.py", line 592, in run_until_complete
self._check_running()
File "C:\Users\drago\anaconda3\envs\itsuki-bot\lib\asyncio\base_events.py", line 552, in _check_running
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
self.loop = asyncio.get_event_loop()
self.bot = self.loop.run_until_complete(__class.context.bot.get_context(self.message))
```still
how can i make on_member_join command
Then just do create task
there's nothing better than that?
async def on_member_join(member):
# member is the person who joined and is the instance of discord.Member
. . . .
Idk, seems like it 🤷♂️
no i am asking what after this?
okay then
Just do whatever u want to do....?
like when member join send message to server
U need to get a channel with Guild.get_channel
or get system channel
Yea
can you send full code
!d discord.Guild.system_channel lol
property system_channel: Optional[discord.channel.TextChannel]```
Returns the guild’s channel used for system messages.
If no channel is set, then this returns `None`.
Of...?
Sorry but I won't spoon feed
!d discord.ext.commands.Cog @brave flint
class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/master/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
(:
Tq
@client.event
async def on_member_join(member):
await guild.get_channel.send('welcome')
You search of that of is it on your mind?
like this?
Not that
get_channel(your channel id)
ok
like this
Well, I have been using the docs command for discord.py since like 2-3 months, so I sort of remember most of the parts. There are still parts which I forget tho 
but i need for all servers bot in
member.guild.get_channel(id)
ok
Than get the guild system channel
I didnt get whats is cog and how to use it sad
its categorys
so also can i make on_member_left command
!d discord.on_member_remove is the correct function haha
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
I don't know my code is right but
def find_first_channel(channels):
position_array = [i.position for i in channels]
for i in channels:
if i.position == min(position_array):
return i
@gaunt herald
ok
I maybe wrong
property text_channels: List[discord.channel.TextChannel]```
A list of text channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
But good try Melon!
LOL

Tnx
GJ!
Can people can be like this?
Like what? Lol
What
^
its just muscle memory remembering the extension/module attributes/classes
But hes awsome
More of, being that free that I remember everything 😂🤣
I don't remember all that 😐
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: user is a required argument that is missing.
what?
Hii
hi
did u invoke the command with a member arg
@bot.command(name="Kick", help="CMD to kick user")
@commands.has_permissions(ban_members=True)
async def kick(self, ctx, member : discord.Member, *, reason = None):
if author.guild_permissions.administrator == false:
await ctx.channel.send("You don't have permission to use this command !")
if member == ctx.message.author:
await ctx.channel.send("You Can't Kick Yourself !")
if member == ctx.message.server.owner:
await ctx.channel.send(f"Woah {ctx.author.mention}, You can't Kick Owner !")
else:
await member.kick(reason=reason)
message = f"You have been kicked from {ctx.guild.name} "
await member.send(message)
await ctx.channel.send(f"{member} Has been Kicked from the server !")
i got this error
U didn't specify a member
this isnt an error hes just missing an arg
Yea
uh i need to "discord.Member" ?
No
no
When u use the command
member = @cinder ruin ?
!kick @boreal ravine JK
U didn't specify that kayle
😂
i did
@_kick.error
async def kick_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("KICK WHO???")
did you invoke the command with a member argument
Who's talking to you lol
I was telling them
That u r missing that arg
I just gave an example...
...
What if they forgot to put the reason kwarg lol
LOL
Then also it will be triggered
he deleted his code nice
reason=None
Oof
LOL
he defined reason as "None"
.
its optional
Yea
Yea
Didn't see it. Oops
It's okay
did he even read his params tho
MissingRequiredArgument: user is a required argument that is missing. what user?
?
uhhhh
check your params
parameters?
yes
It's not user name. It's user mention
Like !kick @brave flint not !kick aloneInSky
oh yea so i need to add user mention?
Umm
yes
Your code is right.
nice
You just need to mention user after your kick command
You don't have to change your code
in the args
yesyes
done but still error
than try this
im osrry i didnt specify my error
@_kick.error
async def kick_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("KICK WHO???")
i think its MissingRequiredArgument
Whats the error?
wait
Isn't it MissingRequiredArgument? or what error?
my error was : raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.
then mention a member in the args
okayyyy
was he mentioned?
yeah he said yes
how to change to code layout?
!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.
i think it was same
@commands.has_permissions(ban_members=True)
async def kick(self, ctx, member : discord.Member, *, reason = None):
if author.guild_permissions.administrator == false:
await ctx.channel.send("You don't have permission to use this command !")
if member == ctx.message.author:
await ctx.channel.send("You Can't Kick Yourself !")
if member == ctx.message.server.owner:
await ctx.channel.send(f"Woah {ctx.author.mention}, You can't Kick Owner !")
else:
await member.kick(reason=reason)
message = f"You have been kicked from {ctx.guild.name} "
await member.send(message)
await ctx.channel.send(f"{member} Has been Kicked from the server !"```
@bot.command(name="Kick", help="CMD to kick user")
@commands.has_permissions(ban_members=True)
async def kick(self, ctx, member : discord.Member, *, reason = None):
if author.guild_permissions.administrator == false:
await ctx.channel.send("You don't have permission to use this command !")
if member == ctx.message.author:
await ctx.channel.send("You Can't Kick Yourself !")
if member == ctx.message.server.owner:
await ctx.channel.send(f"Woah {ctx.author.mention}, You can't Kick Owner !")
else:
await member.kick(reason=reason)
message = f"You have been kicked from {ctx.guild.name} "
await member.send(message)
await ctx.channel.send(f"{member} Has been Kicked from the server !"
@bot.command(name="Kick", help="CMD to kick user")
@commands.has_permissions(ban_members=True)
async def kick(self, ctx, member : discord.Member, reason = None):
if author.guild_permissions.administrator == false:
await ctx.channel.send("You don't have permission to use this command !")
if member == ctx.message.author:
await ctx.channel.send("You Can't Kick Yourself !")
if member == ctx.message.server.owner:
await ctx.channel.send(f"Woah {ctx.author.mention}, You can't Kick Owner !")
else:
await member.kick(reason=reason)
message = f"You have been kicked from {ctx.guild.name} "
await member.send(message)
await ctx.channel.send(f"{member} Has been Kicked from the server !")
try this
if not ctx.author.guild_permissions.administrator:
return await ctx.channel.send("You don't have permission to use this command !")
if member == ctx.author:
return await ctx.channel.send("You Can't Kick Yourself !")
if member == ctx.guild.owner:
return await ctx.channel.send(f"Woah {ctx.author.mention}, You can't Kick Owner !")
else:
try:
await member.send(f"You have been kicked from {ctx.guild.name}")
await member.kick(reason=reason)
await ctx.send(f"{member} Has been Kicked from the server!")
except discord.Forbidden:
pass
oh
class discord.Guild```
Represents a Discord guild.
This is referred to as a “server” in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guild’s hash.
str(x) Returns the guild’s name.
not only in dpy but okay
in other libs too?
try to add , pass_context=True
Yea
Old syntax
😢
Discord API refers to servers as Guild
pass_context is only needed prior to dpy 1.0
It's fine haha
done
No need to do that
no need
eh nvm
Just use dpy 2.0 now
Or any other fork like disnake
imagine self promoting
show us what you did and the error
Eh many are using disnake 🤷♂️
did you copy the code..?
nope im maked the code by myself thats why i asking to you guys
I kick like this
@bot.command(name="kick", pass_context=True)
@commands.has_permissions(administrator=True)
async def _kick(ctx, *, user_name: discord.Member, reason='By. Bot'):
await user_name.kick(reason=reason)
@_kick.error
async def _kick_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("{}~~ can't do that~ LOL".format(ctx.message.author))
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("Kick who")
if isinstance(error, commands.BadArgument):
await ctx.send("Kick who?")
eh copy code > doesn't work > give up
U should make the reason f"Kicked by {ctx.author}"
That's much needed, since sometimes mods become toxic and kick without anyone knowing
Urr yep LOL
u dont need pass_context
**I KNOW THAT 😭 **
Calm down haha
str.format() is cring
Dpy still uses it 🤷♂️
in the docs?
huh?
the docs are like a couple years old
No comments
hm
He just wants u to use f strings that's it
cleaner syntax
more info on formatting strings > https://realpython.com/python-f-strings/
Thanks I will try that
!f-string
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
(:
same thing
---I know I should use cogs but I have to time...
hm
Oh, And I use f strings too...
I just didn't changed the codeeeeeeeeee
Facing this error... I don't really know anything about syntax tbh
Here's the code
@client.command()
async def test(ctx):
embed=Discord.embed(title="Verse",
embed.set_thumbnail(url='https://media.discordapp.net/attachments/879250270176018482/885439670765387776/qxNZR3p3_400x400.jpg?width=300&height=300')
embed.add_field(name="**xhelp**",value="Shows this menu",inline=False)```
And the fact I gotta go.
U forgot to close the bracket
Cya again ;D
ok ill try use that
Indents
@client.command()
async def test(ctx):
embed=Discord.embed(title="Verse")
embed.set_thumbnail(url='h ttps://media.discordapp.net/attachments/879250270176018482/885439670765387776/qxNZR3p3_400x400.jpg?width=300&height=300')
embed.add_field(name="xhelp",value="Shows this menu",inline=False)
bruh
Kk
i thought we fixed your code.. 🤔
Lmao

Oh yea ty
Also indent
Thanks
bad practice
also its discord.Embed() not Discord.embed()
DND
Cya
^
Ah yes that too
😦
does anyone have a list of slash command libraries?
OMG
I'd like to have that tooo
...
ANYONE HERE
!e
print(bool("This is noone in #discord-bots channel. Right? python bot? 😕 "))
@dusk pumice :white_check_mark: Your eval job has completed with return code 0.
True
edpy
basically dpy v2.0 but with slash commands support
so it has slash commands rn?
Yes
ah nice thanks :)
ah nice
disnake
?
U were asking for a slash cmd lib, right?
oh that
Lol
thanks
how do i handle the error when def test(user: discord.Member = None): cant find the user inputed?
Hey I am trying to send an embed using cogs and this is what I get "<nextcord.embeds.Embed object at 0x7f9ff51770d0>"
Here is my code
modules/helps/help_embed/help_embed.py
from nextcord import Color, Embed
BLURPLE = Color.blurple()
help_embed = Embed(
title = 'Help for Efendo bot',
description = """This is the help command
Things inside square brackets `[]` are mandatory
Things inside curly brackets `{}` are not mandatory
""",
color = BLURPLE
)
help_embed.set_author(
name = "Efendo bot the helper"
)
help_embed.set_thumbnail(
url = 'https://media.discordapp.net/attachments/877930996304056404/896632386484305950/efndo_pfp.jpg?width=940&height=588'
)
help_embed.set_footer(
text = "You can use e> helpcmd [command] for more info on a command \n(And yes, this applies to e> help too.)"
)
help_embed.add_field(
name = 'Random commands',
value = "e> 8ball",
inline = False,
)
help_embed.add_field(
name = 'Info commands',
value = "e> ping",
inline = False,
)
help_embed.add_field(
name = 'Moderation commands',
value = """e> kick [member] {reason}
e> ban [member] {reason},
e> unban [member username and member tag]
e> purge [amount of messages]""",
inline = False,
)
modules/helps/cog.py
from nextcord.ext import commands
from .embeds.help_embed import *
class HelpCog(commands.Cog):
def __init__(self, bot:commands.Bot):
self.bot = bot
@commands.command()
async def help(self, ctx: commands.Context):
await ctx.reply(help_embed)
def setup(bot: commands.Bot):
bot.add_cog(HelpCog(bot))
What do I do?
disnake ,
or hikari if you want a non fork library
What error do you get
alright thanks
i have to use
await ctx.send(embed=help_embed) lol
And is Your members intent enabled?
np , sorry i wrote dislash instead of disnake
lol
how do I make my discord bot send a message when 10 of the commands are used such as i have 70 comands when user uses 10 command the bot will say "hey try premium and stuff"
you would need to use a custom check
Count the commands in on_command_completion event and then do check if the user has reached his limit
sure
discord.ext.commands.errors.MemberNotFound: Member "all" not found.
I should all that this is being run in a cog
Show your code
Make a command error handler for this error, as simple as that
@commands.command()
async def warnRemove(self, ctx, user: discord.Member = None, num = None):
if user != None:
print(user.name)
Make a warnRemove error handler as shown here
ahhh ok
And check for the error type you got above
yeah ik, i just dont want it ot break catastrophically when that happens haha
so yeah ,ill add the error handler
cool cool
just trying to make sure someone cant try and warnremove "pog" or something
!ban 887672943268757585 Self-botting
:incoming_envelope: :ok_hand: applied ban to @ionic path permanently.
not cool at all
Hey, how do I get the latency of my bot through a cog.
here is my code
class Ping(commands.Cog, name="Ping Cog"):
def __init__(self, bot:commands.Bot):
self.bot = bot
@commands.command()
async def ping(self, ctx: commands.Context):
await ctx.reply(f"latency of bot is ...")
def setup(bot: commands.Bot):
bot.add_cog(Ping(bot))
!d discord.ext.commands.Bot.latency
property latency: float```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
ye but cog
this attr. gives you the latency in seconds
ik how to do it normally
@client.event
async def on_raw_reaction_add(payload):
user_id = payload.user_id
message_id = payload.message_id
emoji = payload.emoji
guild = client.get_guild(varsfile.server_id)
user = guild.get_member(user_id)
user_roles = user.roles
if message_id == varsfile.gender_message_id:
print('boye')
he_him_role = guild.get_role(varsfile.he_him_id)
she_her_role = guild.get_role(varsfile.she_her_id)
they_them_role = guild.get_role(varsfile.they_them_id)
if (he_him_role in user_roles) or (she_her_role in user_roles) or (they_them_role in user_roles):
print('aight')
else:
print(emoji)
if emoji == "❤️":
await user.add_roles(she_her_role)
elif emoji == "💙":
await user.add_roles(he_him_role)
elif emoji == "💜":
await user.add_roles(they_them_role)```
I have this block of code
when i print the emoji it works very well, but for some reason i dont get the role
i am not getting any error
source = await discord.FFmpegOpusAudio.from_probe("song.mp3")
ctx.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio("song.mp3")))
```which method is better to use?
How to run my bot 24/7
host it
Exception in voice thread Thread-6
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/player.py", line 673, in run
self._do_run()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/player.py", line 666, in _do_run
play_audio(data, encode=not self.source.is_opus())
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/voice_client.py", line 672, in send_audio_packet
self.socket.sendto(packet, (self.endpoint_ip, self.voice_port))
TypeError: str, bytes or bytearray expected, not _MissingSentinel
Exception in voice thread Thread-9
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/player.py", line 673, in run
self._do_run()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/player.py", line 666, in _do_run
play_audio(data, encode=not self.source.is_opus())
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/voice_client.py", line 672, in send_audio_packet
self.socket.sendto(packet, (self.endpoint_ip, self.voice_port))
TypeError: str, bytes or bytearray expected, not _MissingSentinel
``````py
@commands.command()
@commands.cooldown(1, 3, BucketType.member)
async def play(self,ctx):
if ctx.author.voice is None:
return await ctx.send(f'You need to be in a voice channel to use this command')
channel = ctx.author.voice.channel
try:
await channel.connect()
except:
await ctx.guild.voice_client.move_to(channel)
ctx.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio("despacito.mp3")))
await ctx.send(f"Playing your song.")
```help ???
umm how? I'm on mobile can you suggest me any site?
heroku
Is heroku free?
people say not for bot hosting but it did a fine job gfor my bot
yeah gives you like 22 days of uptime in a month
how do I add link in footer embed?
do you mean a hyperlink in the footer?
it is free for a certain extent
yeah
u can always have a 2nd acc and jsut move your bot stuff to that and host it xd hacks
well you can't hyperlink in footers
anywhere else?
in description u can
because I need help to make my discord bot send a message after 10 of its commands are used but i am not able to do that
You can only use hyperlinks in titles, descriptions and field values
Although to do it in the title is a bit different
You'd need to do Embed(title=..., url=...)
hm so it possible in other languages of dscord?
webhooks, embed descriptions, embed field values
help?
no all embeds r the same for every lang
sure
pip file? what are you using?
u cant do pip install is that what you mean?
are you using cmd or replit?
show the error
did you searched on net the library name?
to see is there any spelling mistakes in your cmd or atleast the library exsisted
jesus
holy
dont be ashamed bro, im literally getting indentation errors
and cant figure them out
could have something to do with this
that is above my level apology
like what??? 💀
wtf
show code
How is @unkempt canyon hosted?
iirc on linode
a hosting site
Which one
linode
Ohhh
download the most recent microsoft visual c++ i guess
an IDE error maybe. if it isn't then show me the code above that command
from google
a help here
@bot.command()
async def hgif(ctx):
global lnb
page = requests.get(f'https://.com/tag/anime/')
tree = html.fromstring(page.content)
send = False
while send ==False:
if len(lnb) ==0:
lnb = [x for x in range(1,100)]#regenerate the list
x = random.choice(lnb)
lnb.remove(x)
link = tree.xpath(f"/html/body/div[1]/div/div[2]/div[{x}]/div/a/@href")
if len(link) >=1:
l = link[0]
send= True
if ctx.channel.is_nsfw():
await ctx.send(f' {l}')
else:
await ctx.send('Please turn this channel into nsfw')
error :
lnb is not defined
did you define lnb first somewhere?
actually no
then define it smh
actually these codes work in my og bot but not here
i am trying to do somechanges in it so i am tried 1st running command and doesnt work it works in og bot
hm
Can i add @unkempt canyon for my server?
no ig , the bot's open source tho
The bot is made to function in this server, I doubt it will work in other servers
^
^
🗿
how make !help {some command}
that's the default, you already have that
yes because you're removing the command
remove this line
!help is a dpy builtin
but and type !help dont show custom help
then you might wanna take a look at this:
https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96
Hey, I wanna kick a member using a button but of course my code has errors. here it is.
modules/mod/kick_button.py
from nextcord import *
from .cog import memberToActionKick, reasonToActionKick
class KickButton(ui.View):
def __init__(self):
#stuff
@ui.button(
label = "Kick",
style = ButtonStyle.red
)
async def confirm(self, button: ui.Button, interaction: Interaction):
await interaction.response.send_message(
content = f"Successfully kicked {memberToActionKick} because `{reasonToActionKick}`",
ephemeral = False
)
self.value = True
self.stop()
@ui.button(
label = "Don't kick",
style = ButtonStyle.primary
)
async def cancel(self, button: ui.Button, interaction: Interaction):
await interaction.response.send_message(
content = "Phew that was a close one!",
ephemeral = False
)
self.value = False
self.stop()
if view.value is None:
pass
elif view.value:
await member.kick(reason=reasonToActionKick)
await ctx.reply(f"Successfully kicked {memberToActionKick} because `{reasonToActionKick}`")
else:
await ctx.send('didn\'t kick')
modules/mod/cog.py
@commands.command(aliases=['lolkick', "remove", "yeet"])
async def kick(self, ctx: commands.Context, member: Member, *, reason="No particular reason"):
if ctx.message.author.guild_permissions.administrator or ctx.message.author.guild_permissions.kick_members:
memberToActionKick = member
reasonToActionKick = reason
view = KickButton()
await ctx.send('Are you sure you wanna kick that member?', view = view)
await view.wait()
else:
await ctx.reply("You don't have the permission `kick members`")
What do I do?
well can you help me?
If you don't share any errors we can't help you
oh ur talking abt the error
If you don't say what exactly doesn't work nobody can help you
Just saying "my code doesn't work and has errors" and sharing the code doesn't help us getting more information
sending wait
loaded ping
* Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployment.
* Running on http://172.18.0.208:8080/ (Press CTRL+C to quit)
loaded random
loaded help
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/bot.py", line 661, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 843, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/runner/Efendo-Bot-SRC/modules/mod/cog.py", line 3, in <module>
from .kick_button import *
File "/home/runner/Efendo-Bot-SRC/modules/mod/kick_button.py", line 2, in <module>
from .cog import memberToActionKick, reasonToActionKick
ImportError: cannot import name 'memberToActionKick' from 'modules.mod.cog' (/home/runner/Efendo-Bot-SRC/modules/mod/cog.py)
The above exception was the direct cause of the following exception:
**Traceback (most recent call last):
File "main.py", line 39, in <module>
client.load_extension(f"modules.{folder}.cog")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/bot.py", line 733, in load_extension
self._load_from_module_spec(spec, name)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/bot.py", line 664, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
nextcord.ext.commands.errors.ExtensionFailed: Extension 'modules.mod.cog' raised an error: ImportError: cannot import name 'memberToActionKick' from 'modules.mod.cog' (/home/runner/Efendo-Bot-SRC/modules/mod/cog.py)**
that’s like basic python stuff
why cant it import memberToActionKick?
Ever heard of variable scopes?
As I said, ever heard of scopes?
Look where your variable is defined and think about it's scope
Do I get caught by Copyright if I use the images from Yahoo?
this is not global variable
ik
i didn;t send the top code cuz it was discord word limit
from .kick_button import *
#Top code cuz discord word limit :(
memberToActionKick = 'Nobody'
reasonToActionKick = 'Nothing'
You mean taking a random picture from Yahoo Images or whatever they call it?
Well they offer you copyrighted and non copyrighted pictures
Yahoo doesn't care what you do with them, the owner of the picture does
How do I know if it is copyrighted?
So you can get copyrighted by the owner
All search engines have copyright filter
I should get pictrues in pixabay 
await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") of overwrites with the target (either 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")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
thank you very much bro ❤️
Hunter is really smart

yes haha
No comments on that
haha
hunter accept the compliment smh
Yes he did. HAHA
@errant shuttle teach me js pls
is it necessary
If it is, then thanks :D
: ) haha
hosting bot on heroku is hard af
Hello, can someone tell me why the command doesn't work? It worked perfectly before, I added many commands and it started doing some kind of jokes with me. I deleted all on_message events and every other event except the on_ready one and it still doesn't worked. Everything is fine, the database is working properly, I made some tests and it's doing the things. The only problem is that the bot does not send the embed message. Can someone please tell me what to do, there is not any error shown? One of the command codes: ```python
economy = DiscordEconomy.Economy()
async def is_registered(ctx):
r = await economy.is_registered(ctx.message.author.id)
return r
is_registered = commands.check(is_registered)
@client.command()
@is_registered
async def dep(ctx: commands.Context, money: int):
r = await economy.get_user(ctx.message.author.id)
r = r[2]
embed = discord.Embed(colour=discord.Color.from_rgb(244, 182, 89))
if r >= money:
await economy.add_money(ctx.message.author.id, "bank", money)
await economy.remove_money(ctx.message.author.id, "wallet", money)
embed.add_field(name="Deposit", value=f"Successfully deposited {money} money!")
embed.set_footer(text=f"Invoked by {ctx.message.author.name}", icon_url=ctx.message.author.avatar_url)
await ctx.send(embed=embed)
else:
embed.add_field(name="Deposit", value=f"You don't have enough money to deposit!")
embed.set_footer(text=f"Invoked by {ctx.message.author.name}", icon_url=ctx.message.author.avatar_url)
await ctx.send(embed=embed)```
has anyone used heroku to host a bot? Because my bot does not want to come online
trust me it's really easy you're just doing something wrong 😭
i can run it manually but it does not like heroku
you could try watching a yt walkthrough
I did
the bot does not go online, and what console?
more > view logs
._. there was logs
From D-API, ?tag no heroku
- Bots are not what the platform is designed for. Heroku is designed to provide web servers (like Django, Flask, etc). This is why they give you a domain name and open a port on their local emulator.
-
Heroku's environment is heavily containerized, making it significantly underpowered for a standard use case.
-
Heroku's environment is volatile. In order to handle the insane amount of users trying to use it for their own applications, Heroku will dispose your environment every time your application dies unless you pay.
-
Heroku has minimal system dependency control. If any of your Python requirements need C bindings (such as PyNaCl binding to libsodium, or lxml binding to libxml), they are unlikely to function properly, if at all, in a native environment. As such, you often need to resort to adding third-party buildpacks to facilitate otherwise normal CPython extension functionality. (This is the reason why voice doesn't work natively on heroku.)
-
Heroku only offers a limited amount of time on their free programme for your applications. If you exceed this limit, which you probably will, they'll shut down your application until your free credit resets.
He is seeking for help
Exactly, but I will do it anyways
Not suggestion
Having some extra knowledge about the platform before hand never hurts, this isn't a suggestion it's information which can help sometimes
it's good for small bots
Check your remaining dyno hours
yes
when you run your dynos make sure to check logs for any errors
I did not know about those logs ;-;
well you do now 😂
bunch of import errors 🤦♂️
check your requirements.txt file then 😂
btw the requirements.txt must be outside any other folder that you have
so don't keep it in the module
I'm working on it, and structure is fixed alrd
otherwise heroku won't be able to find it and it won't install your deps
?😅
discord bot create a channel
._. why can't it just show all missing imports at once
says it clearly right here
it's optional and it's a CategoryChannel instance
¯_(ツ)_/¯
would've been faster if you'd know what deps you're using 😂
I have so many imports that it is quite hard to find all of them. And I'm not even using venv for this
¯_(ツ)_/¯
It's online!
gj
still kinda useless when no one uses my bot
¯_(ツ)_/¯
is your bot open source?
oh
the only open-source thing that i have is my disnake-docs project
which basically implements @unkempt canyon's "!docs" commands in disnake
¯_(ツ)_/¯
I have a Discord Music bot but when connecting to voice channel (with ffmpeg), it's taking too long to just perform that operation, sometime it just took 2 seconds, but when the bot left over for 1 hour or a day, It took 60 seconds. (bad grammar, sorry)
vc[ctx.guild.id].play(discord.FFmpegPCMAudio(source=audio[ctx.guild.id], **FFMPEG_OPTIONS))
ffmpeg options:
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5','options': '-vn',}
Hey @nocturne fern! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
it shouldn't really have anything to do with ffmpeg, probably your bot's resources
let me copy that real quick :potatopopcorn:
which one should I download for mongo db?
send.. link.. pls
!pypi disnake-docs
okay cool
never used a program for mongo
the browser was enough for me
hm
this much files... really.. i thought it was just like 100 lines or smth
now how should I copy that :potatopopcorn:
well, @unkempt canyon's docs really has a lot of files 😂
I tried my code on my PC, on my server, and it still have that same problem.
me who litterally writes docs with inspect..
¯_(ツ)_/¯
then idrk, but i'm 100% sure that it has nothing to do with ffmpeg
ok .-.
not bad, right?
yeah looks good
although disnake-docs does it better 😂
i basically took @unkempt canyon's code and improved it a lil' bit by adding buttons pagination and fuzzy search
so music come out from bot sometime freeze because of the bot's resources?
pain
https://github.com/NotFlameDev/itsuki-bot/blob/master/cogs/info.py#L38-L42 if you look at the whole thing
cogs/info.py lines 38 to 42
await ctx.send(embed=discord.Embed(title=query,
url=f"https://discordpy.readthedocs.io/en/stable/"
f"{'' if 'commands' not in query and 'tasks' not in query else url}{'index' if 'tasks' in query else 'api'}.html#{remove(query, '.discord') if inspect.isclass(query) else query if 'discord' in query else 'discord.ext.' + query}",
description=f"```py\n{query.split('.')[-1]}{inspect.signature(eval(query))}```\n{(e.split(f'Attributes{newline}')[0]).replace('`.', f'`{dot.join(query.split(dot)[2:-1]) + dot}').split(f'Parameters{newline}')[0].replace(':meth:`', f'`{query.split(dot)[-2] + dot}').replace('..', '').replace('::', ':').replace('versionadded', 'Version added')}",
color=self.bot.base_color))```
perhaps
;-; ok then
at least it works ¯_(ツ)_/¯
it does but it looks like a mess 😭
gonna add some more mess soon :potatopopcorn:
¯_(ツ)_/¯
you could just clone disnake-docs and change every disnake occurence with discord and it should still work fairly fine
wait, this thing doesn't escape the codeblock?
will do that
i'd love a star btw 🥺
no clue
star mine :potatopopcorn:
how
we star each others 😎
deal
same
ty 🧎♂️
the problem is that no one in my guild uses github ¯_(ツ)_/¯
¯_(ツ)_/¯
so 1 star which is me yay
Hello, can someone tell me why the command doesn't work? It worked perfectly before, I added many commands and it started doing some kind of jokes with me. I deleted all on_message events and every other event except the on_ready one and it still doesn't worked. Everything is fine, the database is working properly, I made some tests and it's doing the things. The only problem is that the bot does not send the embed message. Can someone please tell me what to do, there is not any error shown? One of the command codes: ```python
economy = DiscordEconomy.Economy()
async def is_registered(ctx):
r = await economy.is_registered(ctx.message.author.id)
return r
is_registered = commands.check(is_registered)
@client.command()
@is_registered
async def dep(ctx: commands.Context, money: int):
r = await economy.get_user(ctx.message.author.id)
r = r[2]
embed = discord.Embed(colour=discord.Color.from_rgb(244, 182, 89))
if r >= money:
await economy.add_money(ctx.message.author.id, "bank", money)
await economy.remove_money(ctx.message.author.id, "wallet", money)
embed.add_field(name="Deposit", value=f"Successfully deposited {money} money!")
embed.set_footer(text=f"Invoked by {ctx.message.author.name}", icon_url=ctx.message.author.avatar_url)
await ctx.send(embed=embed)
else:
embed.add_field(name="Deposit", value=f"You don't have enough money to deposit!")
embed.set_footer(text=f"Invoked by {ctx.message.author.name}", icon_url=ctx.message.author.avatar_url)
await ctx.send(embed=embed)```
no one really uses disnake-docs but still got some stars on it 😎
saying "it doesn't work" isn't helpful in any way
try adding some print satements in your command and see where it breaks
let me guess... everyone that stars your repo, you tell them to do that...
shh
guys, I don't understand a week ago I created a mute command and it was great, now it doesn't work anymore and the code is always the same, someone can tell me why?
please, read all the text. I said exactly what does not work :p
add some print statements and see where exactly it breaks
will try
but the code worked before anyway
need some help
can't help you when you didn't provide what the problem is
I have the same problem, but with many commands :/
I just described it to you ...
.
not helpful in any way
uhm
