#discord-bots
1 messages Β· Page 205 of 1
from discord.ext import commands
from pathlib import Path
import json
from discord import Intents
from discord.ext import commands
import platform
import logging
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
cwd = Path(__file__).parents[0]
cwd = str(cwd)
print(f"{cwd}\n-----")
#bot secrets
secret_file = json.load(open(cwd+'/secrets.json'))
bot = commands.Bot(command_prefix="-",intents=intents, case_insensitive=True, owner_id=874530550487060490)
bot.config_token = secret_file['token']
logging.basicConfig(level=logging.INFO)
@bot.event
async def on_ready():
print(f"-----\nLogged in as : {bot.user.name} : {bot.user.id}\n-----\nMy current prefix is: -\n-----")
#another way to use activity
print("-----\nLogged in as: {} : {}\n-----\nMy current prefix is: -\n-----".format(bot.user.name, bot.user.id))
await bot.change_presence(activity=discord.Game(name=f"Hi, my names {bot.user.name}.\nUse - to insteract with me!"))
#bot activity
@bot.command(name='hi', aliases=['hello'])
async def _hi(ctx):
"""
A simple command which says hi to the author
"""
await ctx.send(f"Hi {ctx.author.mention}!")
@bot.command()
async def stats(ctx):
"""
A usefull command that shows the bot statistics
"""
pythonVersion = platform.python_version()
dpyVersion = discord.__version__
serverCount = len(bot.guilds)
memberCount = len([m for m in bot.get_all_members()])
await ctx.send(f"So im in {serverCount} guilds with a total of {memberCount} members. :smiley:\nIm running python {pythonVersion} and discord.py {dpyVersion}")
@bot.command(aliases=['disconnect', 'close', 'stopbot', 'exit'])
@commands.is_owner()
async def logout(ctx):
"""
If the user running this command owns the bot then this will disconnect the bot from discord
"""
await ctx.send(f"Hey {ctx.author.mention}, I am now logging out :wave:")
await bot.logout()
@logout.error
async def logout_error(ctx, error):
"""
Whenever logout command has error this will be tripped
"""
if isinstance(error, commands.CheckFailure):
await ctx.send("Hey! You lack permission to use this command as you do not down the bot.")
else:
raise error
@bot.command()
async def echo(ctx, *, message=None):
"""
A Simple command that repeats the users input back to them
"""
message = message or "please provide the message to be repeated"
await ctx.message.delete()
await ctx.send(message)
bot.run(bot.config_token) ```
@slate swan
asked ya to enable members intent, not just message_content
they are different......
ohh i got it
thnks bro i got the fix
@slate swanbro there is one more error i am using my logout command to stop bot but its not working
can u pls fix it
code and error?
Imagine asking someone to fix something without the error π
Anyways hyd sarth
Someone here to help?
Just ask
my commands are not getting synced smh
Why is it so? How can i fic that
remove the await
because its not under an async function
it only works under async functions
But it needs the await
the loop needs to be under the async function
async def get_option():
under that maybe
try that
Makes no sense
if not, there are other people will come to help you
await cant be worked out of async functions dude
move it under the async function
Make a classmeth
!e
import asyncio
class Cat:
def __init__(self, attr):
self.attr = attr
print(self.attr)
@classmethod
async def setup(cls):
attr = await asyncio.sleep(0, result="meow") # do some setup things
return cls(attr)
async def main():
cat_obj = await Cat.setup()
print(cat_obj)
asyncio.run(main())
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | meow
002 | <__main__.Cat object at 0x7f2cd016a350>
class SelectEditWarn(nc.ui.Select):
def __init__(self, target):
self.target = target
options = []
for case in self.get_options():
options.append(self.get_reason(case[0]))
super().__init__(placeholder="Choose a case", min_values=1, max_values=1, options=options)
@classmethod
async def get_options(cls, target):
async with aiosqlite.connect("maja.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT case_id FROM warning_system WHERE user_id = ? AND guild_id = ?', (target.id, nc.Interaction.guild.id,))
cases = await cursor.fetchall()
return cases
@classmethod
async def get_reason(cls, case_id):
async with aiosqlite.connect("maja.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT reason FROM warning_system WHERE case_id = ? AND guild_id = ?', (case_id, nc.Interaction.guild.id,))
reason = await cursor.fetchone()
new_option = nc.SelectOption(label=str(case_id), description=reason[0])
return new_option
async def callback(self, inter: nc.Interaction):
await inter.response.send_message(content=f"Success")```
That's not how you use class methods
What is wrong?
That's not how you use class methods. After fixing that, you still need to await the coroutine that the method returns
!d classmethod
@classmethod```
Transform a method into a class method.
A class method receives the class as an implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:
```py
class C:
@classmethod
def f(cls, arg1, arg2): ...
``` The `@classmethod` form is a function [decorator](https://docs.python.org/3/glossary.html#term-decorator) β see [Function definitions](https://docs.python.org/3/reference/compound_stmts.html#function) for details.
A class method can be called either on the class (such as `C.f()`) or on an instance (such as `C().f()`). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.
Is not working
bot is not syncing all the slash commands, syncing only one. what do I do?
who can help with tempvoice i try write
@bot.event
async def on_voice_state_update(member, before, after):
# Check if the user joined a voice channel
if before.channel is None and after.channel is not None:
# Move the user to a specific voice channel
channel_id = 1079874258668367933 # Replace with the ID of the voice channel you want to move the user to
channel = bot.get_channel(channel_id)
await member.move_to(channel)```its correct?
u have bot.tree.commands?
if so do this synced =await bot.tree.sync()
it only syncing one command bruh
hmmm
u sure u have more than one command xD
right below the
.
How
!d discord.Client
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
async with x Asynchronously initialises the client and automatically cleans up.
New in version 2.0.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
when i am trying to use my bot's logout command to disconnect bot it is not logging out
okii
` > import discord
from discord.ext import commands
from pathlib import Path
import json
from discord import Intents
from discord.ext import commands
import platform
import loggingEnable all standard intents and message content
(prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
intents.members = Truecwd = Path(file).parents[0]
cwd = str(cwd)
print(f"{cwd}\n-----")#bot secrets
secret_file = json.load(open(cwd+'/secrets.json'))
bot = commands.Bot(command_prefix="-",intents=intents, case_insensitive=True, owner_id=874530550487060490)
bot.config_token = secret_file['token']
logging.basicConfig(level=logging.INFO)@bot.event
async def on_ready():
print(f"-----\nLogged in as : {bot.user.name} : {bot.user.id}\n-----\nMy current prefix is: -\n-----")
#another way to use activity
print("-----\nLogged in as: {} : {}\n-----\nMy current prefix is: -\n-----".format(bot.user.name, bot.user.id))
await bot.change_presence(activity=discord.Game(name=f"Hi, my names {bot.user.name}.\nUse - to insteract with me!"))
#bot activity@bot.command(name='hi', aliases=['hello'])
async def _hi(ctx):
"""
A simple command which says hi to the author
"""
await ctx.send(f"Hi {ctx.author.mention}!")@bot.command()
async def stats(ctx):
"""
A usefull command that shows the bot statistics
"""
pythonVersion = platform.python_version()
dpyVersion = discord.version
serverCount = len(bot.guilds)
memberCount = len([m for m in bot.get_all_members()])
await ctx.send(f"So im in {serverCount} guilds with a total of {memberCount} members. :smiley:\nIm running python {pythonVersion} and discord.py {dpyVersion}")@bot.command(aliases=['disconnect', 'close', 'stopbot', 'exit'])
@commands.is_owner()
async def logout(ctx):
"""
If the user running this command owns the bot then this will disconnect the bot from discord
"""
await ctx.send(f"Hey {ctx.author.mention}, I am now logging out :wave:")
await bot.logout()@logout.error
async def logout_error(ctx, error):
"""
Whenever logout command has error this will be tripped
"""
if isinstance(error, commands.CheckFailure):
await ctx.send("Hey! You lack permission to use this command as you do not down the bot.")
else:
raise error@bot.command()
async def echo(ctx, *, message=None):
"""
A Simple command that repeats the users input back to them
"""message = message or "please provide the message to be repeated" await ctx.message.delete() await ctx.send(message)bot.run(bot.config_token) `
this is my bot's code @shrewd fjord
Kk
!d discord.Client.close
await close()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Closes the connection to Discord.
async def somefunc()
#put the codes from options to options.append
then
asyncio.run(somefunc())
where should i put this
okay leme try
oh thnk u broo it worked
Noice
Any have the time to make an anti-raid bot?
bro make it u r self we will help u if u found any error
I know someone looking for a dev
Ummm
async def _hi(ctx):
"""
A simple command which says hi to the author
"""
await ctx.send(f"Hi {ctx.author.mention}!")``` At *a simple command which says hi to the author* why wont u just use a #?
It's for command discrimination
Description*
Bro i am trippin, it is called "doc strings"
Np
I think thats for the description of the function not the command
Nope, you can use doc strings to describe a command in discord
But yeah, it can be used to describe a function too
Mk, just knew that
Asher, help me fr π
u can describe command function params param uses everything
Ignore that it's replit
I typically use
@commands.Bot.command(brief = "short description", description = "long description")
Tried changing name from .toml and also tried changing the folder name
Still same error like bru
btw we will discuss gist topic in an hour or two are u free?
both work dpy handles it in backend
Will be free after 1 hour
cool
Can you make an anti-raud discord bot?
yeah
aend the whole error
This is the error only
did u set the credentials
Changing name to different like
sra-wrapper, i cant use poetry build
I have someone who needs a dev
are u sure that name is like free no one else has used it
I cant even able to use poetry build dude by changing the name
sra is already taken
and if i take it my old name for example sra, it says this ^^^
!pypi sra
Then i tried changing to sra-wrapper
what was wrong with sra-wrapper?
Then i get module NotFound error on build
Like wtf dude π
send error
Sec
This is poetry build err, it works with sra name when both folder and toml pckg name same
But not for sra-wrapper πΏ
Maybe i need to change repl name?
pyproject.toml
what is name of project?
sra
qlso
Changed it to sra-wrapper
the folder
needs to be sra-wrapper
the folder containing the code
check pokelance
No err on build, sra-wrapper = err on build
I did
show ur file structure
and show toml file
Sec
its probably replit
Yeah sec then
make a new repl and clone it ig
Same error 
Dont tell me to copy paste the codes now fr π
yeah probably repl does some settings in the back
y are u using replit tho use github codespaces no?
Huh?
Drop the link fr, u gave a good idea
It will be easy to integrate with github
From replit it's hard and sometime crashes
Can you explain more?
Got it alr
about the ban command, how do you check role position?
!d discord.Role.position
The position of the role. This number is usually positive. The bottom role has a position of 0.
Warning
Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.
!d attribute
A value associated with an object which is usually referenced by name using dotted expressions. For example, if an object o has an attribute a it would be referenced as o.a.
It is possible to give an object an attribute whose name is not an identifier as defined by Identifiers and keywords, for example using setattr(), if the object allows it. Such an attribute will not be accessible using a dotted expression, and would instead need to be retrieved with getattr().
!d attribute Message
A value associated with an object which is usually referenced by name using dotted expressions. For example, if an object o has an attribute a it would be referenced as o.a.
It is possible to give an object an attribute whose name is not an identifier as defined by Identifiers and keywords, for example using setattr(), if the object allows it. Such an attribute will not be accessible using a dotted expression, and would instead need to be retrieved with getattr().
Command raised an exception: AttributeError: 'Message' object has no attribute 'create_at'
pls help me to fix this error
cuz its a help info when any user will give the cmd -help it will send -hi : A simple command which says hi
pls help me to fix this
**pls fix thiss **
Command raised an exception: AttributeError: 'Message' object has no attribute 'create_at'
created_at
now its showing
AttributeError: 'Context' object has no attribute 'Message'
it's message, not Message
okay i got it
thnks again bro
TypeError: Embed.set_footer() got an unexpected keyword argument 'name' @slate swanbro now pls fix this error
text="..."
name is meant for author, not footer
embed.set_footer(name=bot.user.name, icon_url=bot.user.avatar.url)
this is the code line
!d discord.Embed.set_footer
set_footer(*, text=None, icon_url=None)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
You can check parameters in documentation or use help() in python...
@slate swanbro this is my stats code of bot ```pythonVersion = platform.python_version()
dpyVersion = discord.version
serverCount = len(bot.guilds)
memberCount = len([m for m in bot.get_all_members()])
embed = discord.Embed(title=f'{bot.user.name} Stats', description='\uFEFF', colour=ctx.author.colour, timestamp=ctx.message.created_at)
embed.add_field(name='Bot Version:', value=bot.version)
embed.add_field(name='Python Version:', value=pythonVersion)
embed.add_field(name='Discord.py Version:', value=dpyVersion)
embed.add_field(name='Total Guilds', value=serverCount)
embed.add_field(name='Total Members', value=memberCount)
embed.add_field(name='Bot Developers', value="@dark pilot")
embed.set_footer(text=f"Carpe Noctem | {bot.user.name}")
embed.set_footer(text=bot.user.name, icon_url=bot.user.avatar.url)
await ctx.send(embed) ``` i am getting the output of -stats command as `<discord.embeds.Embed object at 0x00000242E0863D00>
`
pls tell me how to fix it
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=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/latest/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.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/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/latest/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.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
the embed kwarg
what i do to fix
Pass embed on embed kwarg
Here
bro can u pls make a good stats embed code for my bot i am newbie in python
this isn't working
it's not showimg the embed command when I using slash commands```@bot.tree.command(name='embed',description='send an embed')
async def embed(interaction: discord.Interaction):
member=interaction.user
embed_message = discord.Embed(title="Title of embed", description="Description of embed", colour=discord.Colour.orange)
embed_message.set_author(name=f"Request by {member.id}", icon_url=member.avatar)
embed_message.set_thumbnail(url=interaction.guild.icon_url)
embed_message.set_image(url=interaction.guild.icon_url)
embed_message.add_field(name="Field name", value="Field value", inline=False)
embed_message.set_footer(text="This is the footer", icon_url=member.avatar)
await interaction.response.send_message(embed = embed_message)```
what's the problem ?
you need to py get-pip.py
also use pycharm
ok, np :)
i also need help lol, my discord bot wont go online, and i dont think theres any major errors in my code, can anyone help me?
Hey @peak pilot! 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://discord.com/developers/applications
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
oops lol
ty
`import discord
import responses
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
async def send_message(message, user_message, is_private):
try:
response = responses.handle_response(user_message)
await message.author.send(response) if is_private else await message.channel.send(response)
except Exception as e:
print(e)
def run_discord_bot():
TOKEN = '---------------------------------------------------------------'
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'{client.user} is no running!')
client.run(TOKEN)`
how to i put permissions on my slash commands?
if statement
How would i do something like this>
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 489, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 296, in on_application_command_error
raise error
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 888, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\user_moderation\cog.py", line 826, in warn_edit_by_user
dropdown = EditWarnDropdown(member)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\user_moderation\view.py", line 49, in __init__
self.add_item(SelectEditWarn(self.target))
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\user_moderation\view.py", line 76, in __init__
asyncio.run(append_options())
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 33, in run
raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop```
functions not running when i call the command?
import discord
from discord.ext import commands
intents = discord.Intents.all()
client = discord.Client(intents=discord.Intents.all())
bot = commands.Bot(command_prefix='+', intents=intents)```
```python
@bot.command()
async def kick(ctx, *args):```
i've never had this issue before
@tasks.loop(seconds=10)
async def statusloop():
await xdtrol.wait_until_ready()
await xdtrol.change_presence(status=discord.Status.dnd,
activity=discord.Activity(type=discord.ActivityType.watching,
name=f"d"))
await sleep(10)
await xdtrol.change_presence(status=discord.Status.dnd,
ctivity=discord.Game(name="d"))
await sleep(10)
statusloop.start()
im getting erorr
i need hekp with discord-components can someone help me
hey all! i am trying so hard to implement a translation function into my very simple bot and nothing I do seems to work, ill post the code i have
return str(googletrans.Translate'')```
how yall do that slick copy/paste up there
async def on_ready():
print(f'{client.user} is runnin biitch')
@client.event
async def translate(ctx, lang, *, args):
t = Translator
a = t.translate(args, dest=lang)
await ctx.send(a.text)```
!code
thx king
really i jus dk the python code to translate user input, it should work if i can implement it after return str
what on earth is Translator
the google translate thing....
googletrans recommended translator and i switched to translate in return str
idk if it recognizes translate tho
you can't just
idrk python yall bare with me
put Translator and expect it to work
elaborate
I have some problem with the dropdown
in here?
Translator isn't anything
yes
i got this code from a youtube videoooo
also there are other errors but this is the one i'm most concerned about
IDK help a g out
is the code returning an error?
nah, it runs my bot, jus nothing translates
i can still use randfact and roll n stuff
im jus trying to implement a translator somehow and nothin i find on the interweb has worked
Translator simply doesn't exist as a thing
i imported it from the googletrans API
you have imported it into python yes?
import randfacts
import googletrans
from googletrans import Translator```
yes
have you installed the googletrans module?
with pip? yes
ah okay then that should be fine
the main problem in that case is the way you're using the decorator
wdym
@bot.command()
async def translate(ctx, *args):
#code here```
make srue you import discord and discord.ext commands
and all that stuff
help π¦
is imported, but when i use bot command it returns and error and bot wont start no more
i also tried client command and it returned the same thing
AttributeError: module 'discord.ext.commands.bot' has no attribute 'command'
import commands
import discord
import googletrans
from discord.ext.commands import bot
from googletrans import Translator```
@vestal laurel can you help me
im pretty dumb n there is quite a lot going on there, whats ur code look like around those lines
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='PREFIX_HERE', intents=INTENTS_HERE)```
its discord-components
```C:\Users\Jynik Weekes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\nextcord\health_check.py:25: DistributionWarning: discord.py is installed which is incompatible with nextcord. Please remove this library by using pip3 uninstall discord.py
warn(message, DistributionWarning, stacklevel=0)
Traceback (most recent call last):
File "sorrow.py", line 22, in <module>
from discord_components import nextcordComponents, Button, ButtonStyle
File "C:\Users\Jynik Weekes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord_components_init_.py", line 1, in <module>
from .client import *
File "C:\Users\Jynik Weekes\AppData\Local\Packages\PythonSoftwareFound
\\\\\\\\\\\ation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord_components\client.py", line 12, in <module>
from .component import Component
File "C:\Users\Jynik Weekes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord_components\component.py", line 3, in <module>
from discord import PartialEmoji, Emoji, InvalidArgument
ImportError: cannot import name 'InvalidArgument' from 'discord' (C:\Users\Jynik Weekes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord_init_.py)```
this is my friends computer
This looks like it is from discord:
ImportError: cannot import name 'InvalidArgument' from 'discord' (C:\Users\Jynik Weekes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord_init_.py)
Also the first error message:
C:\Users\Jynik Weekes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\nextcord\health_check.py:25: DistributionWarning: discord.py is installed which is incompatible with nextcord. Please remove this library by using pip3 uninstall discord.py
discord.py is installed which is incompatible with nextcord
wait so what do i do
it actually says that word for word
i would uninstall nextcord if you're not using it
Can someone help?
but i am using it
i need discord-components an nextcord
well they are incompatible as it says
maybe try updating them idk
idk what nextcord actually is haha
This is part of the traceback: Please remove this library by using pip3 uninstall discord.py
updating? bruh
listen to the person who actually knows what they're doing lol ^
PS C:\Users\Jynik Weekes\Desktop\sorrow> py sorrow.py
Traceback (most recent call last):
File "sorrow.py", line 22, in <module>
from discord_components import nextcordComponents, Button, ButtonStyle
File "C:\Users\Jynik Weekes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord_components\__init__.py", line 1, in <module>
from .client import *
File "C:\Users\Jynik Weekes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord_components\client.py", line 3, in <module>
from discord import (
ImportError: cannot import name 'Client' from 'discord' (unknown location)```
@velvet compass
tbh jus tell me what i install or uninstall
I'm sorry I don't have the time right now. I'd suggest making a new venv and install from scratch
THANK U OK this has worked, one more question since this is in bot file i have responses file what would be the python command for googletranslating user input
this feller
You can't run async functions from a sync function (like __init__)
Looks like you want to pre-populate your Select with data that comes from an asynchronous source?
So? How then? options must be in init
The best way to do that is to perform said asynchronous lookup somewhere up the "tree" where you do have an asynchronous context, and simply pass that into your __init__
can you help me
Like so:
class MySelectMenu(discord.ui.Select):
def __init__(self, data) -> None:
self.data = data # you can now access `data` from anywhere in the class
async def callback(...) -> None:
...
@bot.command()
async def my_command(ctx: commands.Context, ...) -> None:
# This is inside an asynchronous context, which means you
# can `await` things.
fetch_data = await ... # perform any async operation here
view = discord.ui.View()
view.add_item(MySelectMenu(data=fetch_data))
await ctx.send(view=view)
You still get to use that awaited data in your select menu's __init__
You're just doing that async I/O operation somewhere else
File "C:\Users\Jynik Weekes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord_components\__init__.py", line 1, in <module>
from .client import *
File "C:\Users\Jynik Weekes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord_components\client.py", line 3, in <module>
from discord import (
ImportError: cannot import name 'Client' from 'discord' (unknown location)```
I would recommend getting familiar with this pattern, where you pass information you need from top to bottom (e.g your command handler is at the top, with button subclasses and functions at the button)
don't use 3rd party libraries for components
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
use Views
I dont got it
Oh yeah, sorry. Looks like I sent it before I was even done
Can you have a look at #1080233650047688734
How do you guys think I should handle the voice channels? My idea was to create temporary voice channels for each game and then remove them when empty
So that I could have more then 1 game ongoing at the same time
Any ideas?
is it against discord TOS to make a bot out of a reg client?
You mean, automating the stock discord client?
selfbots are disallowed, you can't log into a user account through automated means
important is based on what your bot does
?
I already did what I needed
ok
async def embed(interaction: discord.Interaction):
member=interaction.user
embed_message = discord.Embed(title="Title of embed", description="Description of embed", colour=discord.Colour.orange)
embed_message.set_author(name=f"Request by {member.id}", icon_url=member.avatar)
embed_message.set_thumbnail(url=interaction.guild.icon_url)
embed_message.set_image(url=interaction.guild.icon_url)
embed_message.add_field(name="Field name", value="Field value", inline=False)
embed_message.set_footer(text="This is the footer", icon_url=member.avatar)
await interaction.response.send_message(embed = embed_message)```
it's not showimg the embed command when I using slash commands
it's supposed to be discord.Colour.orange()
it's a constructor
Ok
Anyone try to make a chat gpt bot with openai api? If few people use chat gpt, bot is stopped and shut down. I maded wrong or something unstable with openai api?
you're probably being rate limited
but you can check your logs and read the error messages
async def embed(interaction: discord.Interaction):
member=interaction.user
embed_message = discord.Embed(title="Title of embed", description="Description of embed", colour=discord.Colour.orange())
embed_message.set_author(name=f"Request by {member.id}", icon_url=member.avatar)
embed_message.set_thumbnail(url=interaction.guild.icon_url)
embed_message.set_image(url=interaction.guild.icon_url)
embed_message.add_field(name="Field name", value="Field value", inline=False)
embed_message.set_footer(text="This is the footer", icon_url=member.avatar)
await interaction.response.send_message(embed = embed_message)```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'user'
commands receive a Context
not an Interaction
Contexts have an author
so you can do py @bot.command(name='embed',description='send an embed') async def embed(context: discord.Context): member=context.author
it'll give me many errors
AttributeError: module 'discord' has no attribute 'contex'
it's uppercase
AttributeError: module 'discord' has no attribute 'Context'
can timeout accept seconds?
yes
discord.ext has the attribute Context
then I have to import it ?
yes, btw how do you defined bot?
wait
no, just remove the type hint
I'm sending the full code
this is why i don't send examples with type hints nobody understands what it does
probably use it as ctx?
it's also not correct, context is part of the commands extension
you are mixing slash commands and message commands together
await timeout(until, /, *, reason=None
What does '/' do?
yes
parameters prior to it are positional only i think
that wont work lmfao
ok I'm putting .tree in middle of them
It very much is valid, Bot.command is defined https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=discord client#discord.ext.commands.Bot.command
until is the time, * is the user, reason is the reason, its enough then why '/'?
the type hint is not correct though, it should actually be discord.ApplicationContext although most people don't even hint the ctx anyway
what's that have to do with context?
but then the slash command isn't showing
bot.command's supply a context parameter
are u using cogs?
hence the error message

That's not how you define a slash command
no
you've defined a normal textual-prefix command
it will be tree
not bot.tree
I send the full code check that
?
in discord.py, slash commands take interaction
hybrid commands take regular context too
the thing is bot.tree.command is not valid slash command registering method but tree.command is
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...

I was thinking of pycord
I suppose OP is using discord.py so that may not be relevant
they're just using vanilla discord.py
prefix commands cant take interaction
it needs to ctx
or context u say
can someone explain me why '/' exists in the timeout func
async def embed(ctx: discord.ctx):
member=ctx.user
embed_message = discord.Embed(title="Title of embed", description="Description of embed", colour=discord.Colour.orange())
embed_message.set_author(name=f"Request by {member.id}", icon_url=member.avatar)
embed_message.set_thumbnail(url=ctx.guild.icon_url)
embed_message.set_image(url=ctx.guild.icon_url)
embed_message.add_field(name="Field name", value="Field value", inline=False)
embed_message.set_footer(text="This is the footer", icon_url=member.avatar)
await ctx.response.send_message(embed = embed_message)```
the argument "until" is positional only
like this ?
no, it's interaction: discord.Interaction, pick slash commands or message commands
where do bot.tree.command coming from
slash
then replace it with interaction
ok
I dont think bot.tree.command work
it does
never worked for me tho
yea It's not showing the slash command
hm
where would tree be defined
I already trien that

!d discord.app_commands.CommandTree.command @unkempt mauve
@command(*, name=..., description=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command from a regular function directly under this tree.
why mention me smh
sorry, i was just letting you know it does exist
I know CommandTree exists
but I have never saw bot.tree.command register slash cmds
When I was a one file dev, I used CommandTree
have you tried the orange thing?
yes
bot.tree is commandtree though
but the slash commands are not getting registered tho
what will do about that?
are they not?? i have never used commandtree.command
yea he is right
i think it does register them
it's not showing the slash command
CommandTree.command does register
you just need to sync
bot.tree.sync()
just do it inside a message command
yes
where to put it ?
like ?
@commands.is_owner()
@bot.command()
async def sync(ctx):
await ctx.send("syncing")
await bot.tree.sync()
!sync
ok
there u go
after the code ?
i like to use the jishaku sync command
on_ready event takes time and sometime discord can ratelimit u
run the command <prefix>sync
https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f#common-caveats
this is why you shouldn't sync in on_ready
async def hello(interaction: discord.Interaction):
"""Says hello!"""
await interaction.response.send_message(f'Hi, {interaction.user.mention}')```Im using this and it's working
I do sync but I dont prefer syncing π
wdym don't prefer syncing?
dont prefer syncing on on_ready
ok
i think it's datetime
discord.ext.commands.errors.CommandRegistrationError: The command sync is already an existing command or alias.
read what the error says
alias?
did u put it somewhere as alias?
there it is
he already put it as cmd
check
it is now one
What !
nothing
btw can u check where u put 'sync' as an alias?
it will help u
ok wait
@commands.is_owner()
async def sync(ctx):
await bot.tree.sync()
await ctx.reply("Synced!")```
this one ?
I put this after the embed command
π
still isn't working
do you have multiple of the same command
yes
it looks like this one is different from the one i sent
so why don't you just fix it
I actually don't know how
by removing it
how is discord.py supposed to know what command to run if there's multiple commands by the same name
just remove it ?
sure
here
what's your code look like?
the slash command isn't showing
have you tried running the sync command...
async def set(self, interaction: discord.Interaction, member: discord.Member, time: datetime.timedelta, reason: str = 'None'):```
remove the typehint
well, there's no time parameter in slash commands anyway
so you'll have to convert it manually from a string
the '/' is the timedelta!?
no I just emoved it
to me?
I mean I tried but same problem
you should remove the second sync command
just keep one of them, because you have two sync commands
I used 1
yes, the / makes the argument positional, your issue is that you can't have a time parameter with slash commands
@unkempt mauve these are all option types you are allowed to use
https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-type
it's not going to show if you don't sync
also, you shouldn't sync in setup_hook either
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)```
like this ?
no
you weren't even using that class to begin with
you can remove it if you'd like
so ?
use a sync command
i'm not sure what was wrong with your other code
but you had two sync commands
I dn't have 2 of them
I removed 1
this one right ?@bot.command() @commands.is_owner() async def sync(ctx): await bot.tree.sync() await ctx.reply("Synced!")
why would it show that error message then
it's not showing an error
it was before
how to fix warning unused import
remove the import
but i want it to make bot it is
import discord
if you're not using it what's the point of keeping it
you don't need the import to make the bot unless you use it
you think the bot will work without importing discord
yes
thanks
have you tried running the sync command?
and why the add command still showing after deleting the command in code
no but how
again, syncing
you have to communicate with discord servers that the command has been deleted
hey
?
hey where are you
AttributeError: 'Guild' object has no attribute 'icon_url'
!d discord.Guild.icon
property icon```
Returns the guildβs icon asset, if available.
and why the add command still sowing ?
do you guys have some simple code to run bot i want to see the different between my code. and yours
yes
what's your run code ?
you can use my bot code but mine is complicated
just anything i will see
here is an old bot
im new to this i just want to make ping pong ctx
bro me too I,m new
ty

i have a new bot that i haven't committed yet
I got this massive ammount of codehttps://paste.pythondiscord.com/yekehoxilo
Hello, I am developing new discord bot now
Is there any guide about discord bots' development that's easy to comprehend for newbies? I have found some but I don't really understand them. And youtube videos, though useful and easy to understand, they posses limited and basic information.
This bot redirect DMs I received from other users to separate channels in category in discord.
I have already completed code in python, but have some problems.
When I receive DMs from others, on_message function doesn't work, it works only if bot receives DMs from other users, not me.
Can anyone help me solve this problem?
how can the bot read your dms lol
the bot can only read its dms
Thanks for your message. Then how do I deal with it?
its impossible. the bot cant read ur dms
Then What can I do to redirect DMs I received from other users to separate channels in category in discord?
DMs cannot be viewed by anyone except the sender and the recipient, and exist in a special channel for this purpose.
thats why DM is a safe place
But I wanna redirect what I received, not other's DMs. isn't it possible?
No
Bots can only read their own DMs
Its impossible for the bot to read your DMs
Then you mean I cannot do anything with DMs I received from others, even simple commands like "copy".
can u clarify what u meant?
Can I even copy the content of DMs with others to the other channels of my server?
only DMs between your bot and people who DM your bot
not between you and other people
This is a better place to ask, is there a way to get the audio of a voice channel with python? Can't find anything about it online. I'm setting up a discord.py bot currently
discord.app_commands.errors.CommandInvokeError: Command 'embed' raised an exception: AttributeError: 'Guild' object has no attribute 'icon_url'how to fix it ?
!d discord.Guild.icon
property icon```
Returns the guildβs icon asset, if available.
Read the docs
I'm keen to setup transcription on my bot, but can't work out how to get a voice channel audio stream...
not possible, it cant read dms between you and other people
async def embed(interaction: discord.Interaction):
member=interaction.user
embed_message = discord.Embed(title="Title of embed", description="Description of embed", colour=discord.Colour.orange())
embed_message.set_author(name=f"Request by {member.id}", icon_url=member.avatar)
embed_message.set_thumbnail(url=interaction.guild.icon_url)
embed_message.set_image(url=interaction.guild.icon_url)
embed_message.add_field(name="Field name", value="Field value", inline=False)
embed_message.set_footer(text="This is the footer", icon_url=member.avatar)
await interaction.response.send_message(embed = embed_message)```
what's the problem here ?
It's changed from guild.icon_url to guild.icon.url
Hey was wondering if a discord bot can do calculations and stuff I can do one to do simple math something that replaces a scientific calculator
oh
The library doesn't provide an interface for this
Not discord.py as of now at least
Sure it can
Gotcha, yeah that sucks
Any other way you can think of that I could achieve this?
Dig through Discord API documentation and find out what you need to interface yourself or get a library that does this for you
You could have the users upload an audio file to the chat probably though
I don't know how to read audio from a file
Yeah was just after the convenience of doing it through a command
Will do
I commend your dedication
Wow I wonder what you all can do with discord bots maybe attach an api with it and make it a type wiki or data information call back etc like what time is it then it tell you time etc
discord.py at least has lower level functions to interface with the gateway, but I don't even know whether voice data from voice channels is sent there
Sure
A Discord bot doesn't have to interface with Discord only
Wow
But in the case of a calculator, it is. That is unless you use a calculator API online π€
Hmmm
Any examples can I see can it attach to google sheets or excel or Jupiter note books?
But discord.py is only an interface to Discord API, so you would need to interface other APIs yourself. The library comes with aiohttp which is an asynchronous HTTP/S request-making-and-processing library, so you can safely use that however you want in your bot program
Β―_(γ)_/Β―
Ye, I do mind that. Why do you need to?
Anyone knows that why AWS EC2 ubuntu server is stop when i webscraping by selenium? Everything is working well on local computer and i set up headless but itβs stop when i try to run on AWS EC2. Is this blocked by amazon?
in the Discord API documents he will not find anything, Voice receiving is not documented (devs have been requesting it for about 4 years)
he could look at the source of pycord and discordjs since these implement voice receiving
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.Cog.listener()
async def on_member_join(self, member):
channel = member.guild.system_channel
if channel is not None:
await channel.send(f'Welcome {member.mention}.')
@commands.command()
async def hello(self, ctx, *, member: discord.Member = None):
"""Says hello"""
member = member or ctx.author
if self._last_member is None or self._last_member.id != member.id:
await ctx.send(f'Hello {member.name}~')
else:
await ctx.send(f'Hello {member.name}... This feels familiar.')
self._last_member = member```why this isn't wrking ?
If it's undocumented doesn't, it mean it's impossible? How did those libraries even know where to look
does it need anything ?
await add_cog(cog, /, *, override=False, guild=..., guilds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a βcogβ to the bot.
A cog is a class that has its own event listeners and commands.
If the cog is a [`app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") then it is added to the botβs [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") as well.
Note
Exceptions raised inside a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog")βs [`cog_load()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.cog_load "discord.ext.commands.Cog.cog_load") method will be propagated to the caller...
it's not impossible, it's just undocumented, about the second question: I don't know, I haven't delved into voice receiving yet, maybe i will in the future (to implement it in disnake) atm i just know op codes
and it doesn't even go against Discord's tos
AttributeError: 'Member' object has no attribute 'avatar_url'
i am getting this error
pls fix this
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
Read the docs
thnks bro i got the fix
pls help me to fix this i am not getting the correct value of server online members
online_members = len([member for member in server.members if member.status != discord.Status.offline])**this is my code for online members **
Presence intents enabled?
umm yep
can u gimme code to enable members intent
The same way you enable any other intent
can u give me i am not getting it
intents.members = True
this is enabled
@vocal snow
And presences too, you are sure
intents = Intents.default()
intents.message_content = True
intents.members = True ```
these all i enabled
@vocal snow
in code ?
OKAY LET ME TRY
@vocal snowthnks bro it fixed
embed = discord.Embed(title="Server Statistics", color=discord.Color.brand_red()) i want to put here a name of the server where -serverinfo command triggred how i do pls tell me
Good day! Please tell me after updating the library discord.py the on_button_click function stopped working, I read the documentation on how to create and process them in a new way, but I did not find such a function. It's just that when I turn off the bot, it "forgets" about all the buttons, and it's not convenient to resend the message every time in a new way.
There's no such event
But what about it? It's just that earlier, even after restarting the bot, it could process clicks, and now it has to send them in a new way
If someone could help :>
< 3
i am trying to make a code that will have the bot play music in discord but not really sure why but it stops in the middle of the song. is there a way to cache it so it wont do that?
@bot.command()
async def play(ctx, source, *, query):
"""Play music from YouTube or Spotify."""
voice_client = ctx.voice_client
if not voice_client:
await ctx.send("I'm not in a voice channel. Use `p/join` to join a voice channel.")
# await voice_channel.connect()
return
# Use youtube_dl to search for and download the audio from YouTube
if source == "youtube":
ydl_opts = {'format': 'bestaudio/best', 'noplaylist': 'True', 'quiet': True, 'default_search': 'auto'}
try:
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(f"ytsearch:{query}", download=False)
url = info['entries'][0]['formats'][0]['url']
except youtube_dl.utils.DownloadError as e:
await ctx.send("An error occurred while trying to play the song.")
print(e)
return
# Use spotipy to search for and get the URI of the track from Spotify
elif source == "spotify":
# query = " ".join(args)
client_credentials_manager = SpotifyClientCredentials()
spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
results = spotify.search(q=query, type='track')
if results['tracks']['items']:
track = results['tracks']['items'][0]
track_name = track['name']
artist_name = track['artists'][0]['name']
album_name = track['album']['name']
album_cover_url = track['album']['images'][0]['url']
url = track['preview_url'] # Add this line to define the url variable
track_url = track['external_urls']['spotify']
message = f"**{track_name}** by **{artist_name}** from the album **{album_name}**\n{track_url}"
await ctx.send(message)
else:
await ctx.send("No results found.")
# If music is already playing, add the new song to the queue
if voice_client.is_playing():
queue.append({'url': url, 'title': info['entries'][0]['title']})
await ctx.send(f"Added {info['entries'][0]['title']} to the queue.")
else:
# Use FFmpegPCMAudio to play the audio
if url:
source = discord.FFmpegOpusAudio(url, before_options='-re', options=None)
voice_client.play(source)
# Send a message to indicate that the bot is playing music
await ctx.send(f"Playing: {info['entries'][0]['title']}")
its give me this error every time or close to it
[tls @ 00000223477bc540] Error in the pull function.
[tls @ 00000223477bc540] IO error: Error number -10054 occurred
[tls @ 00000223477bc540] The specified session has been invalidated for some reason.
Last message repeated 1 times
https://rr2---sn-q4fl6nzy.googlevideo.com/videoplayback?expire=1677676241&ei=cfr-Y7fkG5mH6QK3vYqwAw&ip=8.40.185.18&id=o-AAo1aCFEZcx9yEeuFWZ8YR8eQqh0bE0hl4WUTpGIntBW&itag=249&source=youtube&requiressl=yes&mh=Fv&mm=31%2C29&mn=sn-q4fl6nzy%2Csn-q4flrney&ms=au%2Crdu&mv=m&mvi=2&pl=21&initcwndbps=1813750&vprv=1&mime=audio%2Fwebm&ns=OK3Ov9j3GU9LnqK_QHZrWvEL&gir=yes&clen=1264237&dur=204.001&lmt=1467159253428565&mt=1677654336&fvip=2&keepalive=yes&fexp=24007246&c=WEB&n=TJeBwkaaDi2nKQ&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cvprv%2Cmime%2Cns%2Cgir%2Cclen%2Cdur%2Clmt&lsparams=mh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=AG3C_xAwRgIhAIdZwmb21xpB64EXEzTdgxm6PpNzJxYlZinPkW7cAYCBAiEAkLAbiOJoILnur1J8KfNuamZiqZkoUB1arRGQt2ulvD4%3D&sig=AOq0QJ8wRQIgEhBlnJvS50mF6kfvhBXB5ZJSD4rZaaBN5PP4NdWf4egCIQCWP1vJL9pXQRSZD6e4zdAB7bAILJ8LBtEJx7QFJEAu_g%3D%3D: I/O error
2023-03-01 01:12:58 INFO discord.player ffmpeg process 5784 successfully terminated with return code of 0.
forgot to add rest sorry
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
oh my bad
sure that the spotify lib is async?
How do I handle clicking on the button after restarting the bot, and not create a new button?
<@&831776746206265384>
This
hello, what's up?
their name is Invalid
(in either case that word is not used in that meaning nowadays)
Wdym by that
It means an ill person right?
I think
But also a insult
@tight obsidian what is the correct channel to ask someone to check code for malware and check if it will work
Thereβs no dedicated channel
Is there anything more satisfying than watching millions of Django datetime warnings fly past your terminal
Yes, I have personally witnessed my development IDE crash because the problems tab just kept filling with warning and messages but no actual errors
Anyway wrong channel
Somebody help!!! How can I now handle clicking on the button after restarting the bot, because now there is no on_button_click function that has always handled?
add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.
This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
New in version 2.0.
Can I have a sample code? I'll understand better how to work with it
Has anyone here ever turned a discord bot into a Frankenstein server backend with url routing
what is the command line to put the server name in bot's server info command
If you have a Guild object you can use .name
@vocal snowserver_name = len(server.name)
like this ?
i have tried this but it shows numbers instead of servername
why len()?
π«
I would recommend reading your code to see what's wrong with it lol
'NoneType' object has no attribute 'create_webhook' pls fix this
Hello, everybody, I am back here.
when I run code I attached, code error appeared
await channel.edit(category = category)
^^^^^^^^^^^^
AttributeError: 'DMChannel' object has no attribute 'edit'
Because you can't edit dm channels
pls fixx
You're doing None.create_webhook
And it's giving you an error as you would expect
how to fix this
Then I wanna create DM channel in category with received message, how can I achieve that?
Don't call create_webhook on NoneType
You can't create a DM Channel in a server
A DM Channel is a Direct Message channel; one which is not in a server
You can create a text channel with guild.create_text_channel
Thanks for your help
And send a message there if you want
great
@vocal snowbro i am not getting what u r saying how to fix that attribute error
!e
print(None.create_webhook)
@shrewd fjord :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AttributeError: 'NoneType' object has no attribute 'create_webhook'
This ^^^^
hi im new to python and i want to build a multipurpose bot can some1 help me
Just drop the problem or wues
@commands.has_permissions(administrator=True)
async def antinuke(ctx):
"""
Enables the antinuke system for the server.
"""
# Enable server verification level
await ctx.guild.edit(verification_level=discord.VerificationLevel.high)
# Create server audit log
log_channel = discord.utils.get(ctx.guild.channels, name='audit-log')
await log_channel.create_webhook(name='Antinuke Log')
await ctx.send('Antinuke system enabled.') ``` what is wrong with this code ?
Ques*
log_channel returning None
Try printing log_channel and u will know
.
.
can u gimme the fixed code by editing this @shrewd fjord
Can someone dm me if they can help me make a discord bot on python plzz
Do you have a specific thing you need help with?
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Lots of free courses here; you can filter the results with Beginner difficulty and course/book
Mhm, and if you need help with a specific python concept you can always ask in a help channel ( #βο½how-to-get-help )
Does anyone have the code for a music bot ?
We don't help with most music bots here
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeβs robots.txt file; (b) with YouTubeβs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
(Unless you wanted to make one that plays copyright free music)
Hello, everybody. Who can help me make this kind of discord bot in python?
Process: Bot listens DMs I receive from other users.
Next, bot redirect DMs between me and other users to the server I create.
Next, bot create separate channels for individual DMs in predefined category.
@nextcord.slash_command(name="sug-channel", description="Set the suggestions channel")
@application_checks.has_permissions(administrator=True)
async def sug_channel(self,interaction: nextcord.Interaction,
channel: nextcord.abc.GuildChannel = nextcord.SlashOption(channel_types=[ChannelType.text],name='channel', description='Please select a channel', required=True)):
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS sug (guild INTEGER, channel_id INTEGER)")
await db.commit()
await cursor.execute("SELECT * FROM sug WHERE guild = ?", (interaction.guild.id,))
data = await cursor.fetchone()
if data is None:
await cursor.execute("INSERT INTO sug(guild, channel_id) VALUES (?,?)", (interaction.guild.id, channel.id,))
await db.commit()
await interaction.response.send_message(f"{channel.mention} is the suggestion channel!")
return
if data is not None:
await cursor.execute("SELECT channel_id FROM sug WHERE guild = ?", (interaction.guild.id,))
data2 = await cursor.fetchone()
result = data2[0]
await interaction.response.send_message(f"There is already a suggestion channel in this server!, channel: <#{result}>")
return
await interaction.response.send_message(f"{channel.mention} is the suggestion channel!")
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\interactions.py", line 888, in send_message
await adapter.create_interaction_response(
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\webhook\async_.py", line 204, in request
raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
People just told you it's impossible
you can't redirect, but you can send an invite link to the user inviting them to you server
you'll have to defer the response first
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
await interaction.response.defer()
# do stuff
await interaction.edit_original_response(...)
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
`
@application_command.slash_command(name="mrban", description="Bans a member.")
@commands.has_permissions(administrator=True)
async def ban(self, ctx, member: discord.Member, modreason):
print("Ban1 command used")
confEmbed = discord.Embed(title="Success!", color=member.color)
confEmbed.add_field(name="Banned: ",
value=f"{member.mention} has been banned from the server.",
inline=False)
confEmbed.add_field(name="Reason: ", value=modreason, inline=False)
await ctx.send(embed=confEmbed)
await ctx.guild.ban(member, reason=modreason)
@ban.error
async def ban_error(self, ctx, error):
if isinstance(error, MissingPermissions):
await ctx.send("Sorry, you don't have permissions for that")
if isinstance(error, MemberNotFound):
await ctx.send("Member not found")
if isinstance(error, BadArgument):
await ctx.send("You didn't specify a member or reason")
if isinstance(error, MissingRequiredArgument):
await ctx.send("You didn't specify a member or reason")
`
Here I am using slash commands but the permission check is not happening if someone without permission run this command he/she can easily run it WHYYYY!!!!! HOWW?? I am using has_permission so WHYY.......?
nextcord....
You can't use custom emojis in embed titles
help me :(
you can
Never tried that 
hehe yea embeds are rly weird on which fields gets to use it
it needs to be <:emoji name:emoji id> format
Kind people, tell me what other options there are for responding to pressing the button, I found an example, but there was only:
await interaction.response.send_message('Test', ephemeral=True)
you need the id
Just if we consider the already deceased discord_components, then I need this:
await res.response(type=6)
and if itβs animated i believe itβs :a after
:icon_earlybotdeveloper: or <:icon_earlybotdeveloper:1080454010131189802:a> iirc
oh yeah i see
assuming itβs allowed in titles that should work 
interaction.response.defer is type 6
Thank you, is there any list of all the options? I just can't find
no list, responding with correct type are hidden away, but for interactions
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.InteractionResponse
interaction.response.defer
are used when you dont wanna respond, with optional respond later for message components, while slash is a required respond after deferring.
interaction.response.send_message/edit_message
used for initial response if you dont wanna defer
interaction.followup
this is a webhook you get for followup response after initial interaction, valid for 15 mins
there are also interaction.original_response/edit_original_response/delete_original_response
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.Interaction
HELP ME GUYS PLEASE
`
@application_command.slash_command(name="mrban", description="Bans a member.")
@commands.has_permissions(administrator=True)
async def ban(self, ctx, member: discord.Member, modreason):
print("Ban1 command used")
confEmbed = discord.Embed(title="Success!", color=member.color)
confEmbed.add_field(name="Banned: ",
value=f"{member.mention} has been banned from the server.",
inline=False)
confEmbed.add_field(name="Reason: ", value=modreason, inline=False)
await ctx.send(embed=confEmbed)
await ctx.guild.ban(member, reason=modreason)
@ban.error
async def ban_error(self, ctx, error):
if isinstance(error, MissingPermissions):
await ctx.send("Sorry, you don't have permissions for that")
if isinstance(error, MemberNotFound):
await ctx.send("Member not found")
if isinstance(error, BadArgument):
await ctx.send("You didn't specify a member or reason")
if isinstance(error, MissingRequiredArgument):
await ctx.send("You didn't specify a member or reason")
`
Here I am using slash commands but the permission check is not happening if someone without permission run this command he/she can easily run it WHYYYY!!!!! HOWW?? I am using has_permission so WHYY.......?
nextcord
Why is the a there
Thank you very much
welcome :>
help me π€§π€§
please......
iam*
the has_permissions is not working
it doesnt check if the user got perms or not
hmm
What
i dont have any problem in banning
@naive briar
I have a question. How can I make a embed to last forever and not fail its interaction (buttons, bar) even if the bot gets restarted?
Make it persistent
!d discord.Client.add_view
add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.
This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
New in version 2.0.
where do I put it?
examples/views/persistent.py lines 39 to 45
async def setup_hook(self) -> None:
# Register the persistent view for listening here.
# Note that this does not send the view to any message.
# In order to do this you need to first send a message with the View, which is shown below.
# If you have the message_id you can also pass it as a keyword argument, but for this example
# we don't have one.
self.add_view(PersistentView())```
Will it last even if I restart the bot?
oh, restarting will restart the process! thank you for help. I wanted to make my own ticket system with my server-only bot.
Traceback (most recent call last):
File "C:\Users\USA45\Desktop\New0zeBot\main.py", line 80, in <module>
@bot.slash_command(
^^^^^^^^^^^^^^^^^^
File "C:\Users\USA45\Desktop\New0zeBot\discord\bot.py", line 894, in decorator
result = command(kwargs)(func)
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\USA45\Desktop\New0zeBot\discord\commands\core.py", line 1650, in decorator
return cls(func, attrs)
^^^^^^^^^^^^^^^^^^
File "C:\Users\USA45\Desktop\New0zeBot\discord\commands\core.py", line 640, in init
super().init(func, *kwargs)
File "C:\Users\USA45\Desktop\New0zeBot\discord\commands\core.py", line 181, in init
from ..ext.commands.cooldowns import BucketType, CooldownMapping, MaxConcurrency
File "C:\Users\USA45\Desktop\New0zeBot\discord\ext\commands__init__.py", line 18, in <module>
from .flags import
File "C:\Users\USA45\Desktop\New0zeBot\discord\ext\commands\flags.py", line 71, in <module>
@dataclass
^^^^^^^^^
File "C:\Program Files\Python311\Lib\dataclasses.py", line 1220, in dataclass
return wrap(cls)
^^^^^^^^^
File "C:\Program Files\Python311\Lib\dataclasses.py", line 1210, in wrap
return _process_class(cls, init, repr, eq, order, unsafe_hash,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\Python311\Lib\dataclasses.py", line 958, in _process_class
cls_fields.append(_get_field(cls, name, type, kw_only))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\Python311\Lib\dataclasses.py", line 815, in _get_field
raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'discord.utils._MissingSentinel'> for field name is not allowed: use default_factory
am i able to use wait for message in the on message event?
Why not
it says i cant use await outside a function
how can i check in which cog is an application subcommand?
cant you just click on ur cogs and ctrl f it?
it is for a command list
What? Show the code
apologies i was being dumb
how do I make these commands guild_only?
!d discord.app_commands.guild_only
@discord.app_commands.guild_only(func=None)```
A decorator that indicates this command can only be used in a guild context.
This is **not** implemented as a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check"), and is instead verified by Discord server side. Therefore, there is no error handler called when a command is used within a private message.
This decorator can be called with or without parentheses.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Examples...
I tried it on a few commands (that doesnt has groups) and it worked but on the other (group) commands, it is not working
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
so I need to make a message saying it cant be used in dms
na i think you can make your own check guild only i suppose
how do I check if a slash command was ran in a dm?
!d discord.Interaction.guild
property guild```
The guild the interaction was sent from.
This property will be None
like this?
if interaction.guild is None```?
yes
how to send message like this
```py
<code>
AttributeError: 'NoneType' object has no attribute 'create_webhook'```
@unkempt mauvecan u fix this bro
i am irritated with attributes error
what is the 'NoneType'
idk its not in my code but still showing this
send your code https://paste.pythondiscord.com
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
sent
paste the link
Put your code in https://paste.pythondiscord.com/ and click save and send the link here
when is that printed in the console?
in terminal ?
yes
noo it cames after running cmd -antinuke
is 'log_channel' defined?
i gaved u code bro u can check btw i am newbie so i dont know about python attribute errors
Add a print statement here:
# Create server audit log
log_channel = discord.utils.get(ctx.guild.channels, name='audit-log')
print(f"{log_channel = }")
await log_channel.create_webhook(name='Antinuke Log')
The error says that it cannot find log_channel
!d discord.TextChannel.create_webhook
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
You must have [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") to do this.
Changed in version 1.1: Added the `reason` keyword-only parameter.
should i put this in code @unkempt mauve?
@slate swan can you add a debug print and show the output?
okay let me check
@velvet compassstill not fixed bro
again showing same error
Right, but what did the debug print show
If it showed None, then you know the issue is in this line: log_channel = discord.utils.get(ctx.guild.channels, name='audit-log')
yo can someone help me?
Don't ask to ask π
?
yep it has no errors in debug so how can i fix this
im on vscode and im doing python bot.py and my bot is still offine
read - #βο½how-to-get-help
So it is printing log_channel = some_value
ok
and share the error
Help
not just the issue
no it doesnot showing anything
um u read the error ? remove the "await"
Haha it needs the await
What is output right before the traceback
that same attribute error of webhook
and may i ask why ?
if the await is not there, a coruntine error occurs
Do you mind showing more of the terminal output before the traceback?
okay sending
ERROR discord.client Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\badbo\Desktop\OwnedProjects\security.py", line 77, in antinuke
await log_channel.create_webhook(name='Antinuke Log')
AttributeError: 'NoneType' object has no attribute 'create_webhook'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\badbo\Desktop\OwnedProjects\security.py", line 59, in on_command_error
raise error
File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'create_webhook'
ERROR:discord.client:Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\badbo\Desktop\OwnedProjects\security.py", line 77, in antinuke
await log_channel.create_webhook(name='Antinuke Log')
AttributeError: 'NoneType' object has no attribute 'create_webhook'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\badbo\Desktop\OwnedProjects\security.py", line 59, in on_command_error
raise error
File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'create_webhook'
@velvet compassthis is the error which i am getting after running the cmd
And there is nothing before that?
noo
Hmm
Maybe have a log statement instead of print
But I am pretty sure the issue is because it cannot find that channel, and is returning None
how to fix bro ?
logging.warning(f"{log_channel = }") instead of the print
hm letme check
Which will show in the log messages what the value of log_channel is at that point
I can't access the self argument inside a cog for dynamic cooldown function, so I have tried this:
def drop_cool(msg):
if msg.author.id == 756018524413100114:
return None
elif msg.author.id in list(msg.bot.voted.keys()):
return commands.Cooldown(1, 300)
return commands.Cooldown(1, 600)
```It does work, but sometimes, msg is returned as a `discord.Object` object and I get an attribute error. Why is that and how can I fix it?
If it is None, then you will need to address the line above
Yo I deleted your message because it had your token
again showing that error
oh
Go ahead and reset that as soon as you can
ill cover it
Does that channel already exist?
no
@velvet compass now? ok
can u give a code from which bot will automatically create logs channel
@velvet compass
This looks like it is relevant: https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel
Looks like you haven't saved the file
I don't know hikari, but that looks like a start
ah ok t
ty it worked now
it is showing guild is not defined
@velvet compassthat error got fixed but it is coming with new error -_-
what value should i put there ?
TypeError: Guild.create_text_channel() missing 1 required positional argument: 'self'
How do I get the amount of commands in a cog file? (This is for a subclassed help command)
send the entire code snippet of your command/event
when i run py bot.py the cmd bit disappears and i need to create a new terminal pls help7
okkk
@bot.command()
@commands.has_permissions(administrator=True)
async def antinuke(ctx):
"""
Enables the antinuke system for the server.
"""
# Enable server verification level
await ctx.guild.edit(verification_level=discord.VerificationLevel.high)
# Create server audit log
log_channel = discord.utils.get(ctx.guild.channels, name='audit-log')
guild = discord.Guild
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
guild.me: discord.PermissionOverwrite(read_messages=True)
}
channel = await guild.create_text_channel(name='Antinuke Log', overwrites=overwrites,)
logging.warning(f"{log_channel = }")
await log_channel.create_webhook(name='Antinuke Log')
await ctx.send('Antinuke system enabled.')
@quick gusthere it is
So, I'm learning Python again, instead of learning to code a bot in python and then trying to learn python itself after that, and I need someone to help walk me through discord.py basics. I don't trust tutorials anymore ._.
!d discord.ext.commands.Cog.get_commands
get_commands()```
Returns the commands that are defined inside this cog.
This does *not* include [`discord.app_commands.Command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command") or [`discord.app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") instances.
that's not how you're supposed to do that
.
you use ctx.guild