#discord-bots
1 messages · Page 565 of 1
Do you use the default help command?
yes
@boreal ravine spayle mssql is microsoft SQL
Your bot shouldn’t behave this way tho if you are using the default help command 
Did you subclass it?
I guess it's like, It first looks for that command in it's commands, doesn't find it so sends "Not found" then suddenly finds it in one of the cogs then sends the documentation
the cog? yes
No, the help command
I have not touched the help command yet. I am using the built-in one
Can u send a ss
@reef shell
When it doesn’t find any commands, it returns sending that error message
!d discord.ext.commands.HelpCommand.command_not_found
command_not_found(string)```
This function *could be a* [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A method called when a command is not found in the help command. This is useful to override for i18n.
Defaults to `No command called {0} found.`
then why does it find it later and send it XD
idk why It's happening
Can you check if your bot is running on two instances?
@reef shell jeeeeesus you're a lifesaver and I'm stupid. I have my bot hosted on both replit and local server and I am sure I turned off the replit but somehow it turned back on 😛
The replit version is not updated so it was giving error.
It's working now, thanks
xd
Hi i have this reaction that wont give the role to the user when they react to it
https://paste.pythondiscord.com/obudiweqap.py
here is my code
plz someone
So I have an application on my PC and I want to send the same message that I send on my application onto a discord text channel.
Is there like an event I can use or something
!d discord.TextChannel.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
@dapper cobaltBut this needs to be under an discord.py event, right?
Check https://github.com/ScopesCodez/python-discord-bot if you would like to know how to make Discord bots in Python.
Nono, I'm trying to make it so that when I write something on a seperate desktop application it takes that info and automatically sends it in a discord text channel.
Ah.
Ye
Well, you can get the channel then send the message to it.
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
But can I use discord.TextChannel.send outside of a discord event or command?
Get the channel and if it's a text channel it will return a discord.TextChannel object.
@dapper cobalt Like can you do this:
async def test():
channel = bot.get_channel(903101348000727074)
await channel.send("hello")
and it's not a command or an event
Yes.
As long as bot is your bot's instance, yes.
muterole = discord.Role("Muted")
is this how a role is defined?
get_role(role_id, /)```
Returns a role with the given ID.
import discord
from discord.ext import commands
prefix = ">"
bot = commands.Bot(command_prefix = prefix)
cogs = []
@bot.event
async def on_ready():
print(f'BOT PRINT: Ready')
async def test():
channel = bot.get_channel(903101348000727074)
await channel.send("hello")
bot.run("token")
So like this would work?
Because it's not working for me
Well you did not call the function.
!e
def a():
print("A")
@boreal ravine :warning: Your eval job has completed with return code 0.
[No output]
code
import random
import discord
from discord.ext import commands
import datetime as DT
from discord.ext.commands.errors import MemberNotFound
from discord_slash import SlashCommand
class Info(commands.Cog):
def __init__(self, bot):
self.bot = bot
slash = SlashCommand(bot, sync_commands= True)
#-----------тян-----------#
@slash.slash(name= "тян", description= "С помощью этой команды ты узнаешь кто я такая.")
@commands.command(name= "тян")
async def than(self, ctx):
ping = round(self.bot.latency * 1000)
embed = discord.Embed(
title = 'Кто я?',
description = 'Я не большой бот, зовут меня **Сузуки**, надеюсь запомните.\nКак и все боты в моём стиле я `Тянка`. Ладно что-то я отвлеклась.\n\nЧто я могу? Ну в принципе как все боты я имею команды, для:\n`Модерации`, `Веселья`, `Получения информации`.\n\nНу на этом пока всё. Мой `Семпай` трудится и делает меня \n`Лучше`, `Красивее` и `Продвинутой`.',
colour = 0x694c5f
)
embed.add_field(name= 'Имя:', value= '>>> `Сузуки`')
embed.add_field(name= 'Создатель:', value= '>>> `Барабан4ик#3148`')
embed.add_field(name= 'Пинг:', value= f'>>> `{ping} мс`')
embed.set_footer(text= 'Барабан4ик © 2021 Все права у тянок', icon_url= 'https://cdn.discordapp.com/avatars/637685929611493422/32b105aa2097b6a3a84b2cda2f7b8e00.png?size=128')
await ctx.reply(embed = embed)
error
606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\Baraban4ik\Desktop\Suzuki\cogs\info.py", line 7, in <module>
class Info(commands.Cog):
File "C:\Users\Baraban4ik\Desktop\Suzuki\cogs\info.py", line 11, in Info
slash = SlashCommand(bot, sync_commands= True)
NameError: name 'bot' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Baraban4ik\Desktop\Suzuki\bot.py", line 51, in <module>
bot.load_extension(f"cogs.{filename[:-3]}")
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.info' raised an error: NameError: name 'bot' is not defined
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x000001AA2E05D6C0>
It still doesn't work
You should do that only in the main file.
the library must have some different slash command implementation in cogs for sure
i dont know what library is that so no idea
hm
ye
@cog_ext.cog_slash is the decorator you would use while making a slash cmd in a cog
File "C:\Users\Baraban4ik\Desktop\Suzuki\cogs\info.py", line 13, in Info
@cog_ext.cog_slash(name= "тян", description= "С помощью этой команды ты узнаешь кто я такая.")
NameError: name 'cog_ext' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Baraban4ik\Desktop\Suzuki\bot.py", line 51, in <module>
bot.load_extension(f"cogs.{filename[:-3]}")
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.info' raised an error: NameError: name 'cog_ext' is not defined
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x000001CA3F7CD6C0>
!d discord.Status.offline
The member is offline.
!d discord.ext.commands.Bot.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter.
you need these two
Can someone advise me functional library for discord api?
there is no error.
But there are no commands.
Why is it not working?
@bot.command()
async def avatar(ctx, *, avamember : discord.Member=None):
userAvatarUrl = avamember.avatar_url
await ctx.send(userAvatarUrl)
Ты загружаешь вообще этот ког? Нигде не могу заметить
English please
slash commands take upto 2 hrs to register
Sry, anyway, he is not that perfect at English
о ты русский
def setup(bot):
bot.add_cog(Info(bot))
print("Ког Инфо роботает")
Okay then, np
У тебя выводит принт?
да
why it is not workin?
ведать в этом проблесма
!rule 3
e wrong rule
*4
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
It’s not perfect rule, he’s native language is Russian, so he’ll better understand in Russian
didnt understand
May some1 pls tell what i am doing wrong?
@bot.command()
async def avatar(ctx, *, avamember : discord.Member=None):
userAvatarUrl = avamember.avatar_url
await ctx.send(userAvatarUrl)
But, sorry
we understand
english is my 2nd language as well
maybe because of the *
sorry
any error? and did you restart the bot?
Version of discord.py?
👍
Any errors?
Version of discord.py?
whats that?
whats the error
no member named .... found?
and the bot should be running
aight i'll send
hm
or maybe NoneType has no attribute avatar_url :3
@rain ridge tell me the version of discord.py, pls
wait
maybe
The error while running cmd in discord
Traceback (most recent call last):
File "/home/ranveer/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/media/ranveer/New Volume/VS Code/Practice/Bot/main.py", line 98, in avatar
userAvatarUrl = avamember.avatar_url
AttributeError: 'NoneType' object has no attribute 'avatar_url'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/ranveer/.local/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/ranveer/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/ranveer/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'avatar_url'```
oh
Exactly
nonetype
so , you did <prefix>avatar
and you except it to send your avatar right?
the person does not exist...
its a None value
Ugh, mistaken
i did not
@bot.command()
async def avatar(ctx, avamember : discord.Member=None):
if not avamember: avamember = ctx.author
userAvatarUrl = avamember.avatar_url
await ctx.send(userAvatarUrl)
now it worked 
This will be better
why it always happen
it works when you mention someone
Now it works no matter you mentioned someone or not
so i have to set the value if no one is pinged then it takes user's avatar
avamember = avamember or ctx.author```
thx guys it working now 
and the bot should be running?
To add slash commands to the server
Ofc...
How will you send the Slash Commands to the API lol
?
yes or no
it takes 2 hours
how to make it so that when you mention a bot, it will send a message, for example, its prefix?
You can alwYs specify guild_ids kwarg to register it only in select guilds for testing
!d discord.Member.mentioned_in
mentioned_in(message)```
Checks if the member is mentioned in the specified message.
ty
message.guild.me returns a discord.Member object
hm
ok
heh
i need client(bot) bruh @maiden fable
Didn't I tell u....?
just define
isn't that what I told him
It's fine
And now how long to wait
If u specified the guild ids kwarg, they register instantly
strangely it does not appear
Can I see some code?
@cog_ext.cog_slash(name= "тян", description= "С помощью этой команды ты узнаешь кто я такая.", guild_ids= [894452684072046652])
async def than(self, ctx):
ping = round(self.bot.latency * 1000)
embed = discord.Embed(
title = 'Кто я?',
description = 'Я не большой бот, зовут меня **Сузуки**, надеюсь запомните.\nКак и все боты в моём стиле я `Тянка`. Ладно что-то я отвлеклась.\n\nЧто я могу? Ну в принципе как все боты я имею команды, для:\n`Модерации`, `Веселья`, `Получения информации`.\n\nНу на этом пока всё. Мой `Семпай` трудится и делает меня \n`Лучше`, `Красивее` и `Продвинутой`.',
colour = 0x694c5f
)
embed.add_field(name= 'Имя:', value= '>>> `Сузуки`')
embed.add_field(name= 'Создатель:', value= '>>> `Барабан4ик#3148`')
embed.add_field(name= 'Пинг:', value= f'>>> `{ping} мс`')
embed.set_footer(text= 'Барабан4ик © 2021 Все права у тянок', icon_url= 'https://cdn.discordapp.com/avatars/637685929611493422/32b105aa2097b6a3a84b2cda2f7b8e00.png?size=128')
await ctx.reply(embed = embed)
Weird
hello
Is there any error?
no
Like what I'm importing
full code
import random
import discord
from discord.ext import commands
import datetime as DT
from discord.ext.commands.errors import MemberNotFound
from discord_slash import cog_ext
class Info(commands.Cog):
def __init__(self, bot):
self.bot = bot
#-----------тян-----------#
@cog_ext.cog_slash(name= "тян", description= "С помощью этой команды ты узнаешь кто я такая.", guild_ids= [894452684072046652])
async def than(self, ctx):
ping = round(self.bot.latency * 1000)
embed = discord.Embed(
title = 'Кто я?',
description = 'Я не большой бот, зовут меня **Сузуки**, надеюсь запомните.\nКак и все боты в моём стиле я `Тянка`. Ладно что-то я отвлеклась.\n\nЧто я могу? Ну в принципе как все боты я имею команды, для:\n`Модерации`, `Веселья`, `Получения информации`.\n\nНу на этом пока всё. Мой `Семпай` трудится и делает меня \n`Лучше`, `Красивее` и `Продвинутой`.',
colour = 0x694c5f
)
embed.add_field(name= 'Имя:', value= '>>> `Сузуки`')
embed.add_field(name= 'Создатель:', value= '>>> `Барабан4ик#3148`')
embed.add_field(name= 'Пинг:', value= f'>>> `{ping} мс`')
embed.set_footer(text= 'Барабан4ик © 2021 Все права у тянок', icon_url= 'https://cdn.discordapp.com/avatars/637685929611493422/32b105aa2097b6a3a84b2cda2f7b8e00.png?size=128')
await ctx.reply(embed = embed)
def setup(bot):
bot.add_cog(Info(bot))
print("Ког Инфо роботает")
discord_slash
how to detect mentioned role within a command?
???
@spiral frigate что у тебя случилось ?
!d discord.Role.mentioned_in
Welp nvm
U gotta see role_mentions
!d discord.Message.role_mentions
A list of Role that were mentioned. If the message is in a private message then the list is always empty.
пошли в личку тут нельзя
на русском
я знаю, dm me
Please take it to DMs
Not allowed to talk in another language
Ah cool
i did but didn't know
i tried
async def role(ctx,role : discord.Role =''):
didn't work
Use on_message
i want it to be a command
so what doesn't work
were i create a category with certain roles permissions, so i want the bot to detect roles mentioned
help
help us in helping u
guys, dis guy wants make slash command
any idea?
where's the part that doesn't work
self is an str
u don't use it out of cogs either
I saw that
so why self
what do you want to do with it
why self ?
what's get
its not cog
ok
remove self, and type client.get....
i just need the bot to detect a mentioned role in a certain command like here
async def createCategory(ctx,Role='',*, text=''):
this doesn't work when typing this
admin_role = discord.utils.get(ctx.guild.roles, name=Role)
getting this error:
Command raised an exception: InvalidArgument: target parameter must be either Member or Role
don't exist
switch the parameters
pass in a string in name kwarg
what parameters
!d discord.utils.get
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
I'm really dumb
don't switch the parameters
what did you type in discord, what roles are there?
"admin" role i need to create a new category with access for this role
so why don't you typehint to discord.Role
then mention the role in the command
then u wouldn't have to use get()
didn't work
let me redo it and send the error sorry xd
Code:
import random
import discord
from discord.ext import commands
import datetime as DT
from discord.ext.commands.errors import MemberNotFound
from discord_slash import cog_ext
import discord_slash
class Info(commands.Cog):
def __init__(self, bot):
self.bot = bot
#-----------тян-----------#
@cog_ext.cog_slash(name= "тян", description= "С помощью этой команды ты узнаешь кто я такая.", guild_ids= [894452684072046652])
async def than(self, ctx):
ping = round(self.bot.latency * 1000)
embed = discord.Embed(
title = 'Кто я?',
description = 'Я не большой бот, зовут меня **Сузуки**, надеюсь запомните.\nКак и все боты в моём стиле я `Тянка`. Ладно что-то я отвлеклась.\n\nЧто я могу? Ну в принципе как все боты я имею команды, для:\n`Модерации`, `Веселья`, `Получения информации`.\n\nНу на этом пока всё. Мой `Семпай` трудится и делает меня \n`Лучше`, `Красивее` и `Продвинутой`.',
colour = 0x694c5f
)
embed.add_field(name= 'Имя:', value= '>>> `Сузуки`')
embed.add_field(name= 'Создатель:', value= '>>> `Барабан4ик#3148`')
embed.add_field(name= 'Пинг:', value= f'>>> `{ping} мс`')
embed.set_footer(text= 'Барабан4ик © 2021 Все права у тянок', icon_url= 'https://cdn.discordapp.com/avatars/637685929611493422/32b105aa2097b6a3a84b2cda2f7b8e00.png?size=128')
await ctx.reply(embed = embed)
def setup(bot):
bot.add_cog(Info(bot))
print("Ког Инфо роботает")
problem:
There are no slash commands at all there is no error
Library:
Discord.py
paid for copying code and then not understanding it
I'm gonna guess the person gave you the code used cogs
and he had a get function in the cog
I have already added 'applications.commands`
a really complex one
how to make it so that when you mention a bot, it will send a message, for example, its prefix?
use on_message
bot = ['@rotund oxide']
@commands.Cog.listener()
async def on_message(self, message):
author = message.author
msg = message.content.lower()
if msg in bot:
await message.channel.send(embed=discord.Embed(description=f"My prefix is {message.channel.prefix}"))
didnt help
on_message
!d discord.ext.commands.Bot.user
property user: Optional[discord.user.ClientUser]```
Represents the connected client. `None` if not logged in.
!d discord.Member.mentioned_in
mentioned_in(message)```
Checks if the member is mentioned in the specified message.
doesnt work
did you use what I just sent?
nah
well what do you expect then
tbh didnt understand how to use it
msg = message.content.lower()
where i need put it ?
im a bit dumb, ik
ohk, ty
told u
the person u copied had a get function in the cog
you also have to move to cogs
?
or set the function somewhere and be able to know how to use it
basic python
you're gonna make me really mad if you continue
- define the function
- use it
everything that is in dpy is usable
ty guys!
if you need something else, import it
now all works!
nice
Hello guys i need help with discord.py slash commands
do someone know why it's not working?
@bot.command()
async def badges(ctx, user: discord.Member = None):
await ctx.send(discord.PublicUserFlags_all())```how i can make it print ur badges?
what the heck
really?
this is just pure shitposting
no
oh it's very sad
someone knows?
what no
it's not
f
ok
!d discord.Member.public_flags
property public_flags```
Equivalent to [`User.public_flags`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.public_flags "discord.User.public_flags")
@bot.command()
async def badges(ctx, user: discord.Member = None):
await ctx.send(user.public_flags) this should work?
from this?
oh
a list would come out
UH
with names in it
okey, i will try and then i implement it to a userinfo
can you write what to replace here
import random
import nextcord as discord
from discord.ext import commands
import datetime as DT
from discord.ext.commands.errors import MemberNotFound
from discord_slash import cog_ext
import discord_slash
why you even listening to him
OK
U DO BRO
why
This is not a Modmail thread.
i have pycramp
go to packages, and then install discord
but i don't really use it
the first package
I swear this guy's just shitposting
can you write what to replace here
import random
import nextcord as discord
from discord.ext import commands
import datetime as DT
from discord.ext.commands.errors import MemberNotFound
from discord_slash import cog_ext
import discord_slash
ok
wtf is nextcord
just go to packages and then install discord
from discord.ext import commands and do this (?)
just let him be
he copies code for money, doesn't understand it and then tries to force people to use some fork or smth
<PublicUserFlags value=128> what does this mean XD? @slate swan
that's... probably an id of a badge?
object.__repr__(self)```
Called by the [`repr()`](https://docs.python.org/3/library/functions.html#repr "repr") built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form `<...some useful description...>` should be returned. The return value must be a string object. If a class defines [`__repr__()`](https://docs.python.org/3/reference/datamodel.html#object.__repr__ "object.__repr__") but not [`__str__()`](https://docs.python.org/3/reference/datamodel.html#object.__str__ "object.__str__"), then [`__repr__()`](https://docs.python.org/3/reference/datamodel.html#object.__repr__ "object.__repr__") is also used when an “informal” string representation of instances of that class is required.
This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.
how i can make that a emote of the badge i want?
you can’t, it’s a representation of the object
you need to use whatever attributes of that flag to make the emote badges or whatever
for example a mapping of flag name to emote
the bot doesn't accept brackets
hm, anyways, UserPublicFlags is an iterable
what
meh then no
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\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 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\Baraban4ik\Desktop\Suzuki\cogs\info.py", line 6, in <module>
from discord_slash import cog_ext
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\__init__.py", line 9, in <module>
from .client import SlashCommand # noqa: F401
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\client.py", line 9, in <module>
from discord.ext import commands
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Baraban4ik\Desktop\Suzuki\bot.py", line 51, in <module>
bot.load_extension(f"cogs.{filename[:-3]}")
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 733, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\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 'cogs.info' raised an error: ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0000015251C43AC0>
learn python please
i dont understand what u were saying bruh
it’s stuff you should already know
considering you’re using dpy
public_flags has some attributes that are usable
help
they all return true if the user has those badges
for badge, is_set in user.public_flags:
if is_set and (emoji := getattr(constants.Emojis, f"badge_{badge}", None)):
badges.append(emoji)
yep, they have all of the emojis, which they add if the user has the right badge
???
Install discord-py-interactions with pip
install
Did what?
And what does it show? Sorry but I can't see your screen from where I am...
Error is explained
i did every youtube toturile
1: Uninstall discord.py
2: Use commands.Bot instead of discord.Client
like all of the discord slash command
Just read the error, everything is explained
2: Use commands.Bot instead of discord.Client
?
You have nextcord and discord.py installed. Only use one
what
Stop using discord.Client(), use commands.Bot()
nextcord has support for slash commands
yes?
why doesnt my ban command work its just not working anymore after like a few months
try:
await user.ban(user,reason=None, delete_message_days=7)
print (f"{user.name} Was Banned")
except:
pass
have u defined user?
send whole code
yes ofc
what worng with line 4
where there is
what
i did
i will do again
i did
yes i use
OK
GUYS
i did pip uninsall dsicord.py
and now it's doing only one eroor
for member in ctx.guild.members:
for user in list(ctx.guild.members):
if not user.bot:
try:
await user.ban(user,reason=None, delete_message_days=7)
print (f"{user.name} Was Banned")
yes i know its a bit sketchy but its for my penetration bot thats in my github
omg it's doing again
how do i make my bot log my server votes
i did
do u want my code? i dont know whats wrong
it is in his github, the command its well done
what the
i think (?)
k
ay thx
yes bro u told me it was defined XD
i dont know cogs
replt
I'm writing code with vs code
yes but he is using replt
and pychram
is there any thing in dpy like on_message_delete or on_message_edit
pyCharm is ok ? @slate swan
in vs code it's just don't wanna to install discord.py
for me
it's very good
ok guys i think i need to move to discord.js
gtg byeeeeeeeeeeeeeeeeeeeeeeee
i will try and if it's not good i will come back
X
You can move to forks of discord.py or to other libraries such as hikari
D
but why u start with slash commands directly @shy bane first try something like ctx.send("hello world ")
idk
Hello, everyone! Is there a way for me to make my Discord bot detect the HypeSquad house that the user is in and the user's name?
And/or.*.
i did a 50 commands bot
i know how to do it but the slash command is not working for me
idk the hypesquad, but the username u can use {user.mention} or {user.nickname} i think
Okay. Thank you! :).
but dont change to js just for that u know xd?
you welcome, if i find any way to see the hypesquad i tell u, im trying to make a userinfo with badges but idk
Ah! Thanks a lot and that sounds cool!
I never used it and it worked fine tho
@commands.command(name= "профиль")
async def profile(self, ctx: commands.Context,member:discord.Member = None, guild: discord.Guild = None):
if member == None:
embed = discord.Embed (
title = 'Ваш профиль',
colour = ctx.message.author.color
)
t = ctx.message.author.status
if t == discord.Status.online:
d = "🟢 В сети"
t = ctx.message.author.status
if t == discord.Status.offline:
d = "◉ Не в сети"
t = ctx.message.author.status
if t == discord.Status.idle:
d = "🌙 Не активен"
t = ctx.message.author.status
if t == discord.Status.dnd:
d = "⛔ Не беспокоить"
embed.add_field(name= "Ник:", value = ctx.message.author.mention)
embed.add_field(name= "Статус:", value=f"`{d}`")
embed.add_field(name= "Основная роль:", value = ctx.message.author.top_role.mention)
embed.add_field(name= "Дата создания:", value = f"<t:{int(ctx.message.author.created_at.replace(tzinfo=DT.timezone.utc).timestamp())}:D>")
embed.add_field(name= "Дата присоединения:", value= f"<t:{int(ctx.message.author.joined_at.replace(tzinfo=DT.timezone.utc).timestamp())}:D>")
embed.add_field(name= "Количество ролей:", value=f"`{len(ctx.message.author.roles)- 1}`")
embed.set_thumbnail(url=ctx.message.author.avatar_url)
await ctx.reply(embed = embed)
!d discord.Member.public_flags
property public_flags```
Equivalent to [`User.public_flags`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.public_flags "discord.User.public_flags")
else:
embed = discord.Embed (
title = f'Профиль **{member.display_name}**',
colour = member.color
)
t = member.status
if t == discord.Status.online:
d = "🟢 В сети"
t = member.status
if t == discord.Status.offline:
d = "◉ Не в сети"
t = member.status
if t == discord.Status.idle:
d = "🌙 Не активен"
t = member.status
if t == discord.Status.dnd:
d = "⛔ Не беспокоить"
embed.add_field(name= "Ник:", value = member.mention)
embed.add_field(name= "Статус:", value=f"`{d}`")
embed.add_field(name= "Основная роль:", value = member.top_role.mention)
embed.add_field(name= "Дата создания:", value = f"<t:{int(member.created_at.replace(tzinfo=DT.timezone.utc).timestamp())}:D>")
embed.add_field(name= "Дата присоединения:", value= f"<t:{int(member.joined_at.replace(tzinfo=DT.timezone.utc).timestamp())}:D>")
embed.add_field(name= "Количество ролей:", value=f"`{len(member.roles)- 1}`")
embed.set_thumbnail(url=member.avatar_url)
await ctx.reply(embed = embed)
how to create a random commands in discord.py?
@profile.error
async def profile_error(self, ctx, error):
if isinstance(error, MemberNotFound):
embed = discord.Embed (
title = 'Команда `s~профиль`',
description = 'Команда `s~профиль` выведет основную \n информацию о тебе или о другой милашке. ',
colour = 0x694c5f
)
embed.add_field(name= "Информацию которою я знаю:", value = ">>> `Ник`, `Статус`, `Основная роль`, `Дата создания`...", inline= False)
embed.add_field(name= "Использование:", value = ">>> `~s профиль` `<Участник>`", inline= False)
embed.add_field(name= "Параметры:", value = ">>> `<>` - Необязательный параметр \n `()` - Обязательный параметр", inline= False)
embed.add_field(name= "Пример 1:", value = ">>> `s~профиль` \n ⮩ Выведет информацию о вас", inline= False)
embed.add_field(name= "Пример 2:", value = ">>> `s~профиль` `<Участник>` \n ⮩ Выведет информацию о участнике", inline= False)
await ctx.reply(embed = embed)
but u use like
@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, user: discord.User): # i dont remember the user thing
the command does not work
*User
Thanks.
oh yes
@slim whale
Nope never did
any error?
there is no error
idk, u need to import random (?)
Random
it's just that the bot is not responding
u need to do it for every command, if not idk
Could you give me an example of this, please? I'm not the best at this. I'm kind of new.
your error handler is hiding the error , remove it or add py else : raise error
toit
other work
Its only one tho
when u do a command u need to put that
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 168, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Baraban4ik\Desktop\Suzuki\cogs\info.py", line 143, in profile
embed.set_thumbnail(url=ctx.message.author.avatar_url)
AttributeError: 'Member' object has no attribute 'avatar_url'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 995, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 895, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 177, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'
Im still thinking why did it work and not anymore
Hello! How to create scheduler which doesn’t reset tasks on bot restart?
@bot.command()
async def badges(ctx, user: discord.Member = None):
await ctx.send(repr(user.public_flags.all()))```how i can make this to print more than one badge?
you can use something like <a user/member object>.public_flags this returns all the public badges a user has
you can then iterate thru it as in a list
i have discord.py
Awesome. Thanks!
your python environment maybe , do you have multiple versions of python installed?
i think yes
btw how do u use the reddit api
i got 3.10 3.9 and 3.7 i think
if i put this in the ctx.send it will send the name of the badge?
how do i uninstall some
im pretty new to using the reddit api, and by new i mean i have no idea about it
you can choose which one you want to use , what ide/editor are u using rn
oo ok
how does it work?
I had written this in my project, just how to make it@slim whale
do u know how?
?
random cmd
what?
idk what are u saying xd
yes sure , but i wont spoonfeed that , just look at what i sent above
does anyone know how to use the reddit api?
^this @slate swan ?
I'm speak persian. my english is not good
the praw library?
yes
dont worry im from spain, to do that i imported this import random
from random import sample
okay, i will try
idk, the goal im looking for is fr my bot to be able to post random memes after the user says a certain command, like dank memer
Traceback (most recent call last):
File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\pynput\_util\__init__.py", line 162, in inner
return f(self, *args, **kwargs)
File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\pynput\keyboard\_win32.py", line 280, in _process
self.on_press(key)
File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\pynput\_util\__init__.py", line 78, in inner
if f(*args) is False:
File "pepepopo.py", line 20, in on_press
asyncio.run(send_message())
File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\asyncio\runners.py", line 43, in run
return loop.run_until_complete(main)
File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "pepepopo.py", line 18, in send_message
await channel.send(str(key))
File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\abc.py", line 856, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed, nonce=nonce)
File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\http.py", line 165, in request
async with self.__session.request(method, url, **kwargs) as r:
File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client.py", line 1012, in __aenter__
self._resp = await self._coro
File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client.py", line 426, in _request
with timer:
File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\helpers.py", line 579, in __enter__
raise RuntimeError('Timeout context manager should be used '
RuntimeError: Timeout context manager should be used inside a task
def on_press(key):
print(key)
async def send_message():
print("peepeepoopoo")
channel = bot.get_channel(903101348000727074)
await channel.send(str(key))
asyncio.run(send_message())
pepe = 1
if 1 == pepe:
listener = keyboard.Listener(on_press = on_press)
listener.start()```
it doesnt give me any options but one
oh nvm
so you would be using https://pypi.org/project/asyncpraw
here's a quick start guide : https://asyncpraw.readthedocs.io/en/stable/getting_started/quick_start.html
oh ok, ty
anyone??
yeah
what are they called together
help please
Hellpppp
sorry to bother but, the async praw thingy is kinda confusing, can you gimme a brief rundown?
if thats fine with u
i know but i cant see the on_message_delete ones and other of it kinds
you're probably on 2.0, use member.avatar instead
i found
!d discord.on_message_delete
discord.on_message_delete(message)```
Called when a message is deleted. If the message is not found in the internal message cache, then this event will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.
If this occurs increase the [`max_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") parameter or use the [`on_raw_message_delete()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_message_delete "discord.on_raw_message_delete") event instead.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
how do I convert a tuple to a string? I tried doing it like this:
@bot.command()
def claim(*role_arg):
# prepare (role:req)
claimable = ['based lord:5', 'big:10', 'u:20']
role_f = ''.join(list(role_arg))
role_f = role_f.lower()
however, if I try to do claim based lord it returns basedlord instead of based lord
BUT I kind of have a member variable in his avatar I don't need in this action
your error stated that ctx.message.author.avatar_url is the error, where author is a discord.Member, it doesn't have avatar_url, you need to use avatar instead since avatar_url was removed in 2.0, just do ctx.author.avatar, should be fine
You can use *, role_arg instead of *role_arg, or put a space inside the string at ''.join(list(role_arg)) (' '.join(role_arg))
ok
n e e d a s s i s t a n c e
n e e d a s s i s t a n c e t o o
N E E D A S S I S T A N C E F I R S T
@slim whale
await ctx.guild.ban(user)
thats part of my code that doesnt work anymore i tried mentioning all the users in the guild and it worked so thats how i know it doesnt work
i did
Well what is this in?
Like is it in a command
maybe ctx isn't giving you the guild?
Maybe you have to get the guild object too
In this video, we will learn how to get data from Reddit using python for a Discord bot. We will make the meme command in this video.
If you have any suggestions for future videos, leave it in the comments below.
Some Useful Links -
Reddit Applications- https://reddit.com/prefs/apps
My Discord Server- https://discord.gg/TXF3hBj
My Twitter...
ayyyyyyyyyyyyyyyy ty ty ty
everything is good it just doesnt ban people and everything is defined
absolute legend
np good luck
tysm
Alright, now someone save me
S A V E M E P L S
no save me
y o u f i r s t
we both dont know do we
Lol nope
same
your bot is already running an event loop, use asyncio.create_task instead
Okay, I understand nothing.
Asyncio.create_task where
And where am I running and event loop?
@bot.event
async def on_raw_reaction_add(payload):
if payload.channel_id == 866024988901638185 and payload.emoji.name == ":cantrash:":
channel = bot.get_channel(614467771866021944) ^^^ - EOL while scanning literal
message = await channel.fetch_message(payload.message_id)
reaction = get(message.reactions, emoji=payload.emoji.name)
if reaction and reaction.count > 1:
await message.delete()
on your asyncio.run, since you're trying to run a coroutine in a blocking way
Ohhhhh, so just replace asyncio.run with asyncio.create_task
sure, you need to read more on event loop if you have no idea what i meant
Alright, and that is in the asyncio docs?
def on_press(key):
print(key)
async def send_message():
print("peepeepoopoo")
channel = bot.get_channel(903101348000727074)
await channel.send(str(key))
asyncio.create_task(send_message())
pepe = 1
if 1 == pepe:
listener = keyboard.Listener(on_press = on_press)
listener.start()
Unhandled exception in listener callback
Traceback (most recent call last):
File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\pynput\_util\__init__.py", line 162, in inner
return f(self, *args, **kwargs)
File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\pynput\keyboard\_win32.py", line 280, in _process
self.on_press(key)
File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\pynput\_util\__init__.py", line 78, in inner
if f(*args) is False:
File "pepepopo.py", line 20, in on_press
asyncio.create_task(send_message())
File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\asyncio\tasks.py", line 381, in create_task
loop = events.get_running_loop()
RuntimeError: no running event loop
I see, are you not even running the bot
just use the bot's loop then, bot.loop.create_task
prefix = ">"
bot = commands.Bot(command_prefix = prefix)
def on_press(key):
print(key)
async def send_message():
print("peepeepoopoo")
channel = bot.get_channel(903101348000727074)
await channel.send(str(key))
asyncio.create_task(send_message())
pepe = 1
if 1 == pepe:
listener = keyboard.Listener(on_press = on_press)
listener.start()
@bot.event
async def on_ready():
print(f'BOT PRINT: Ready')
# Calling functions:
bot.run("token")
alright let me give it a shot
fuck yeah, got it
Thanks 😄
Finally
about the event loop part, asyncio docs doesn't talk about it in a walkthrough so
gotta learn it somewhere idk i forgot where i read it
Oh alright, do I just google "event loops python"?
actually i believe this is a good one https://realpython.com/async-io-python/
❤️ tysm

why u do ctx?
it would be user.ban()
Let me try
okay
@bot.command()
async def badges(ctx, user: discord.Member = None):
await ctx.send(str(user.public_flags.all()))```can someone help me? the bots only prints one badge and it prints this [<UserFlags.hypesquad_brilliance: 128>]
how many badges does the user have
i have one but i tried it with a friend and it prints the same
even tho he has more
yes
Nothing
send whole code
if you're talking about the nitro badge, it's because discord doesn't give bots that information
how can I add this error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.3.value: Must be 1024 or fewer in length.
to my error handler?
@_profile.error
async def profile_error(self,ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(error)```
ohhh
but boost badge? im going to try it
elif isinstance(error, HTTPException)
@slim whale 
no it doesnt @slate swan
@bot.command()
async def ban(ctx, user: discord.User): leaving this at the top i think
badges no
na it doesn't, i believe anything subscription badge wise discord wont let the bots know
im going to try with a partner friend
@slate swan it works [<UserFlags.partner: 2>, <UserFlags.hypesquad_bravery: 64>], but how i can make it print another thing?
whats the "another thing"
Like Partner, bravery hypesquad
without the userflags.parter: 2 etc
Extension 'cogs.Commands' raised an error: IndentationError: expected an indented block (Commands.py, line 114)
@_profile.error
async def profile_error(self,ctx, error):
if isinstance(error, commands.CommandOnCooldown):
elif isinstance(error, HTTPException):
await ctx.send(error)```
you mean you only want the name?
Yes
then make it an emoji, for a userinfo
user.public_flags supports iter which returns (name, value) where value is a boolean
so just make a list comp that filter out value that is false, to just get the name
dont understand
what its a iter first of all xd?
hello how do you make the dropdown thing s and buttons without dpy 2.0 because I can't download it
iter is a built-in function that returns a generator which you can iterate through, in simple term, you can for loop whatever iter returns,
for example ```py
user = bot.get_user(80088516616269824)
list(iter(user.public_flags))
[('staff', False), ('partner', False), ('hypesquad', False), ('bug_hunter', False), ('hypesquad_bravery', False), ('hypesquad_brilliance', False), ('hypesquad_balance', True), ('early_supporter', True), ('team_user', False), ('system', False), ('bug_hunter_level_2', False), ('verified_bot', False), ('verified_bot_developer', False), ('discord_certified_moderator', True)]
[x for x, v in iter(user.public_flags) if v]
['hypesquad_balance', 'early_supporter', 'discord_certified_moderator']
last step its list(iter etc
or the x for x
the list comp is the last step
list(iter(user.public_flags)) is just what you would see if you're only casting it to a list without filtering
and then i need to do ctx.send(list) ?
Am i wrong or it needs an else condition too?
it doesn't, you're probably thinking of a ternary statement
>>> and what does this mean? spaces?
>>> is just what you get in a live repl, ```py
print("abc")
abc
no, look, what you need to do is just [x for x, v in iter(user.public_flags) if v], since iter returns a generator of (name, value) pair, you can filter out the names where value is True
how can I add this error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.3.value: Must be 1024 or fewer in length.
to my error handler?
@_profile.error
async def profile_error(self,ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.message.delete()
await ctx.send(error, delete_after=5)```
everything i've tried hasn't worked
but i need to put more names to the filter no?
no?
Just like other errors
!d discord.ext.commands.errors.CommandInvokeError
exception discord.ext.commands.CommandInvokeError(e)```
Exception raised when the command being invoked raised an exception.
This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError")
in that code v is your Boolean, it is True when the user has that badge, and False when the user doesn't have that badge, if v means if v is True, then append them in a list, it would look the same as ```py
badges = []
for x, v in iter(user.public_flags):
if v:
badges.append(x)
so it will only append if `v` is True
how? i have tried so many ways
Guys, I am using discord_slash, but the commands arent loading, what do I do?
So i've copped this piece of code from stackoverflow and i have never coded with the discord api before and it's giving me a nonetype error when i try to send the dm message. why is that?
Token = # censored
client = discord.Client()
@client.event
async def on_ready():
yourID = "469610757512888322"
discordUser = client.get_user(yourID)
await discordUser.send('gibberish')
client.run(Token)
fetch_user
thanks
class discord.DMChannel```
Represents a Discord direct message channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channel’s hash.
str(x) Returns a string representation of the channel
now you caught me off guard, where should i implement it?
And vscode is wanting me to use "fetch_by_id"
first import it
from discord import DMChannel
then, just use: DMChannel.send(fetched_Id, messaged)
how can i make my bot refuse an input and tell someone to send another message if its over a certain amount of characters?
huh, no dont
where do you want to implement it?
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
sure
just a minute
line number?
unfortunately, its made with cogs, otherwise i would have been able to help
guys please can you help with my problem? #help-cheese
does that make it harder?
I just never used cogs
ah okay
if len(UserReply.content) > amount
return
where does that go?
top of the command
So you have to put a while loop. Before your wait_for
and indent the rest of the code outside the if statement
In that loop ask the user for the input
there is a timeout option too tho
Yes, he has to request the input until the amount is correct
So in the while loop ask for the input, check the len, if it satisfy your condition then break the loop, else continue with the loop
You have to break the loop even if the timeout is triggered
Extension 'cogs.Commands' raised an error: SyntaxError: invalid syntax (Commands.py, line 45)
Can you show your code?
i've never worked with while loops, how would i implement it?
Bro then you have just to quit wathever you are doing and study python
Is not possible to make a discord.py bot if you don't know python
this is legit the last thing i need then my bots done lol
i started learning python today and wrote all that
And that seems good but I had just a rapid look and i found a lot of errors and no-sense things
I guessed that you are starting learning discord.py but i hoped that you already knew python lol
for filename in os.listdir('./src/commands/ticket'):
if filename.endswith('.py'):
j1mk0l.load_extension(f'ticket.{filename[:-3]}')
nope lol i learnt both same time xD
i need this bot for my friends and too poor to pay for a dev so have to learn myself
It's bad 😂😂
Python is pretty easy, you can learn it in less than a week
Study the basics and then the Object Oriented basics in python and you're good to start
i will definitely start looking at it more in depth from now, i am having a lot of fun learning
What is the error?
and now im getting this
@slate swan ```py
@bot.command()
async def badges(ctx, user: discord.User = None):
if user is None:
user = ctx.author
list(iter(user.public_flags))
[('staff', False), ('partner', False), ('hypesquad', False), ('bug_hunter', False), ('hypesquad_bravery', False), ('hypesquad_brilliance', False), ('hypesquad_balance', True), ('early_supporter', True), ('team_user', False), ('system', False), ('bug_hunter_level_2', False), ('verified_bot', False), ('verified_bot_developer', False), ('discord_certified_moderator', True)]
badges = []
for x, v in iter(user.public_flags):
if v:
badges.append(x)
await ctx.send(x)
oh
forgot await xd
so you can help me with where to implement pls?
async def askQuestion(question):
await ctx.author.send(question)
print(f"Waiting for reply from {member}...")
userReply = await self.bot.wait_for('message', check=check)
while len(UserReply.content) > 1000:
ctx.author.send("too many characters")
if len(UserReply.content) < 1000:
break
print(f"{member} replied")
return userReply.content
``` @placid skiff
this is what my code looks like while i try using a loop
it sends the question but doesn't progress when i reply
@client.event
async def on_message(message, ctx, suggestion):
if message.channel.name != "suggestions":
return
await message.add_reaction('✅')
await message.add_reaction('❌')
embed = discord.Embed(title="no c", description=f"cc", colour=discord.Colour.light_gray())
embed.add_field(name="Sugestie dał {ctx.author.name}", icon_url = {ctx.author.avatar_url}, inline=False)
embed.add_field(name="Mowa sugestia!", value=f"{suggestion}", inline=False)
await ctx.send(embed=embed)
``` its code
Check if the userReply.content is an empty string
How do I join different strings in an array?
some know
async def askQuestion(question):
await ctx.author.send(question)
print(f"Waiting for reply from {member}...")
next_step = false
while next_step:
userReply = await self.bot.wait_for('message', check=check)
if len(userReply) < 1000:
print(f"{member} replied")
return userReply.content
else:
next_step = true
lookingFor = await askQuestion(questions[0])
lookingTags = await askQuestion(questions[1])
``` can someone tell me why this doesn't progress past Waiting for reply from r0yal#2029... ? it just never continues after you reply
async def send_message():
global keys, count
await bot.get_guild(903101348000727070).get_channel(903101348000727074).send(" | ".join(keys))
print(len(keys))
keys = []
def on_press(key):
global keys, count
keys.append(str(key))
count += 1
if count >= 20:
count = 0
print("ppppppeeeeeennnnnn")
bot.loop.create_task(send_message())
pepe = 1
if 1 == pepe:
listener = keyboard.Listener(on_press = on_press)
listener.start()
Can you have multiple bot.loop.create_task(send_message()) of these loops running at once if you don't cancel them before declaring another one? The bot is supposed to get all of the characters I type on my keyboard, store those characters in the keys array, wait until there are 20 characters in total, and then executes the send_message function, then that function clears the keys array once it sends all of the 20 characters in my text channel. Everything works except for actually sending the message because there seems to be some issue here: py async def send_message(): global keys, count await bot.get_guild(903101348000727070).get_channel(903101348000727074).send(" | ".join(keys)) print(len(keys)) keys = [] Essentially, my question is: is there something running in the background or something I'm missing/ doing wrong here that is making the bot send the characters I type on my keyboard send to my text channel in weird and wrong ways?
if listener.start() blocks the event loop, your task wont run
yes because its blocks the execution
How do I fix that?
not use a blocking library
Well listener is supposed to be non-blocking
# ...or, in a non-blocking fashion:
listener = keyboard.Listener(on_press=on_press, on_release=on_release)
listener.start()
^ From docs
hm, give me a second
Alright, thanks by the way
what library is that
keyboard
ok thanks
😬 sorry
its fine
alright so it seems like it isnt blocking, when does it exactly run your function?
and is the event loop running somewhere?
Well the function is ran really randomly like i don’t understand it’s sequence at all
And what do you mean by event loop?
the asyncio event loop, for example, is the bot running
Oh, yeah the bot is up
The function gets sent but not at the right times
Could this be because I have a slow connection?
And I’m hosting on my internet
(While it’s slow)
Yeah, I’ll send now
async def send_message():
global keys, count
await bot.get_guild(903101348000727070).get_channel(903101348000727074).send(" | ".join(keys))
print(len(keys))
print(keys)
keys = []
def on_press(key):
global keys, count
keys.append(str(key))
count += 1
print(count)
if count >= 20:
count = 0
print("ppppppeeeeeennnnnn")
bot.loop.create_task(send_message())
pepe = 1
if 1 == pepe:
listener = keyboard.Listener(on_press = on_press)
listener.start()
So I added one in send_message
and another in on_press
And this is the output
That is the number of characters I've typed
and then that longer thing is the print(keys) in send_message
and that 31 that you see in the output is from print(len(keys)), which is supposed to 0 before printing that long output.
@hasty iron
does it always delay the execution?
It's pretty random, but yeah always. Let me double check
Ohhhh
Okay so for the first execution it works correctly
I think
But then it doesn't work again for another like 40 messages
There is something wrong in the loops I think. @hasty iron
hm
it's either that or my internet is the problem
Because I just don't understand what else could cause it
Is there like another completely different way I can do this, you think?
no sorry i cant think of anything
Alright, thanks anyways
🤔
😅
what type of a code am i looking at
almost everything in that code is wrong
I'm so confused to why this isn't working can someone help figure it out?
@commands.Cog.listener()
async def on_member_join(member):
print(f"{member.name} joined.")
```There is no errors
how do i add all intents and do i have to add something in the portal?
!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.
show all of the code in that file
import discord
import pymongo
from pymongo import MongoClient
import os
from discord.ext import commands
class BalCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_join(member):
print(f"{member.name} joined.")
def setup(bot):
bot.add_cog(BalCog(bot))
Could it be something to do with my cogs?
do you have intents?
so that all the intents?
yeah this is in main.py
import discord
from discord.ext import commands
from discord import Intents
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="#", intents=intents)
no, go to ur bots dev portal and youll see all of the intents
are you loading the cogs?
no like in the script
Yes heres the entire main.py
import discord
from discord.ext import commands
from discord import Intents
import os
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="#", intents=intents)
bot.remove_command("help")
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
@bot.event
async def on_ready():
print(bot.user.name + " is online.")
bot.run("token")
thanks
you need to add self as the first arg
ah its ur indents
its supposed to be 4 not 8
so right under def init
the event
Yeah
it needs to be indented only 4 spaces
I understand, so like this?
@commands.Cog.listener()
async def on_member_join(member):
print(f"{member.name} joined.")
``` this part of code needs to be indented only 4 spaces
ye
missed out self
How do I do {member.name} with their tag
instead of just their username
is it like this?
user.username+"#"+str(user.discriminator)
just {member}
oh really
the __str__ formats it with the discriminator already
Is there a way to do something for every user existing in a server except bots?
loop over guild.members, check if not member.bot
Even if it was cog, self should've been the first parameter not second cough
So like this?
guild = ctx.guild
member = guild.members
account = {"_id":f"{member.id}","username":f"{member}","balance":"0"}
for guild.members:
if not member.bot:
collection.insert_one(account)
that's not how you use a for loop in python
your indent is wrong
the account variable won't be updated for each member
so not exactly how you'd do it 😛
Don't mean to spoon feed, but this might be what you looking for...```py
guild = ctx.guild
for member in guild.members:
if not member.bot:
account = {"_id":f"{member.id}","username":f"{member}","balance":"0"}
collection.insert_one(account)
does anybody know how to get a groupchat from its id?
like py gc = bot.get_groupchat(123456789) or sumthing
when i do bot.get_channel(gc_id) it returns ```py
None
Hello everyone, how to make the text look like it is from python?
Thanks!!
I am trying to make a bot that kicks unverified members, when i run it and type the command, nothing happens. Anyone know why? @bot.command(pass_context=True) async def kickem(ctx): guild = ctx.guild for member in tuple(guild.members): if len(member.roles) == 1: await bot.kick(member)
does anybody know how to get a groupchat from its id?
like
gc = bot.get_groupchat(123456789)
or sumthing
when i do bot.get_channel(gc_id) it returns
None
Wouldn’t that be impossible as you need to be a friend with a user to add ‘‘em to a group but you can’t friend a bot
Yeah, I think thats not doable
I believe it’s member.kick()
still nothing
Why’re you using pass_context=True?
When I hover my cursor over else it says "Expected Expression" and is underlined red therefore meaning there is something wrong with it. How do I fix this?
if user is None:
results = collection.find({"_id":f"{ctx.author.id}"})
for result in results:
bal_em = discord.Embed(title = f"{ctx.author.name}'s Balance", description = f"{ctx.author} has a balance of " + result["balance"],colour=0xFFA500)
await ctx.send(embed=bal_em)
else:
results = collection.find({"_id":f"{user.id}"})
for result in results:
bal_em = discord.Embed(title = f"{user.name}'s Balance", description = f"{user} has a balance of " + result["balance"],colour=0xFFA500)
await ctx.send(embed=bal_em)
pass_context=True is from > 1.0
@bold oxide
I went scouring around trying to see if something could work
you cant do that im pretty sure
I'm making a counter bot what would be some good info to store in database
hello how can I change the activity of my bot to something like 'picking random stocks' with discord.py
I dont think u need a db for that
I'm still doing it
What
What am I going to use if I don't use a database
How would I get the current number
For multiple servers
And b able to tell the difference between each servers
Can you elaborate on what ur bots gonna do
Umm sure
It's going to join the server and someone will use the command Count! Create [goal number]
It will create a channel say Counting-[goal number]
And it will send a message like the goal is number let's do this
And they will count
And when they reach number it says congrats and I'll add some options for owner to tweak with
Ok
First, store the channel id so you can isolate the counting to only be able tow work in that
Ok
I'm sure u know how to do something like that
Mhm
And then to get the last number, tell them to send something like end before sending the last number, then you can use wait_for to get the last number
That makes sense to me
Ok, try making that
i need a temp mute command please
We don't spoon feed in this discord server
finished = discord.Embed(title="Versai Applications", description=f'Your Answer for Question 12: `{a10.content}`\nAre you sure you want to submit? Please react below!', color = discord.Colour.blue())
print("first mark")
msg = await ctx.author.send(embed=finished)
await msg.add_reaction(checkmark)
await msg.add_reaction(xmark)
print("second mark")
def check(reaction, user):
print("3rd mark")
return all((user.id==ctx.author.id, reaction.message.id==msg.id, str(reaction.emoji) in (checkmark, xmark)))
print("4th mark")
reaction = (await self.bot.wait_for('reaction_add', check=check))[0]
if str(reaction.emoji) == checkmark:
print("5th mark")
I get 0 errors and when i run it it gets to the 3rd mark before not working. Anyone know why? It works perfectly fine in the main server when someone runs it
thats when your bot tries to do something it cant and yes
how to make bot not respond to dm
@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.
This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
^
forbidden means: cant do
yes?
my program uses requests to send an embed to discord webhook, how can I randomise the colour of the embed??
just change the color?
yup
your sending the embed
yup
just change the color
bruh
!d discord.Color.random
hm
i dont think it would work on requests
i am on phone sorry so I dont have code
hm
but i am not using py em=discord.Embed()
where do i add it im really bad at making bots
wait why are u using requests to send a webhook
i am usingpy requests.post('webhook', json=data)
below @bot.command()
hm
whats data?
Json data for embed
{"embeds":[
{
"title":"test"}]}```
need to randomise colour
wdym
hm
👍 thx
👍
DISCORD EMBEDSA/????? WOHA
ok
what
i dont have @bot.comamnd in my code
i use if message.content.startswith
then check if the author isn't the guild owner
why is every bot named bender
I don't think you can in discord.py
uh
idk
More like gender bender 😳😏
Not possible
That's a bug
a bug


