#discord-bots

1 messages Β· Page 205 of 1

brazen raft
#

Unless you pass intents a variable

slate swan
#
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

slate swan
#

they are different......

#

ohh i got it

slate swan
#

@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?

radiant bough
#

Anyways hyd sarth

white citrus
#

Someone here to help?

naive briar
#

Just ask

unkempt mauve
#

my commands are not getting synced smh

white citrus
#

Why is it so? How can i fic that

unkempt mauve
#

remove the await

#

because its not under an async function

#

it only works under async functions

white citrus
#

But it needs the await

unkempt mauve
#

async def get_option():

#

under that maybe

white citrus
#

Not mayby

#

I need some professionel help

unkempt mauve
#

try that

white citrus
#

Makes no sense

unkempt mauve
#

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

naive briar
#

!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())
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | meow
002 | <__main__.Cat object at 0x7f2cd016a350>
white citrus
# naive briar Make a classmeth
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")```
naive briar
#

That's not how you use class methods

white citrus
#

What is wrong?

naive briar
#

That's not how you use class methods. After fixing that, you still need to await the coroutine that the method returns

#

!d classmethod

unkempt canyonBOT
#

@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.
white citrus
unkempt mauve
#

bot is not syncing all the slash commands, syncing only one. what do I do?

glass forge
#

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?
spice zenith
#

if so do this synced =await bot.tree.sync()

unkempt mauve
spice zenith
#

u sure u have more than one command xD

unkempt mauve
spice zenith
#

print(f"Synced {len(synced)} command(s)")

#

put that

spice zenith
unkempt mauve
#

this is why I hate cogs

unkempt mauve
#

help meh

#

the bot is only syncing 1 command

#

when theres 2

#

fixed

shrewd fjord
#

How

slate swan
#

AttributeError: 'Bot' object has no attribute 'logout'

#

how to fix this

shrewd fjord
#

!d discord.Client

unkempt canyonBOT
#

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").
slate swan
#

when i am trying to use my bot's logout command to disconnect bot it is not logging out

shrewd fjord
#

Check if there is a logoff or logout method

#

Wait lemme check

slate swan
#

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 logging

Enable all standard intents and message content

(prefix commands generally require message content)

intents = Intents.default()
intents.message_content = True
intents.members = 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) `

#

this is my bot's code @shrewd fjord

shrewd fjord
#

Kk

shrewd fjord
unkempt canyonBOT
#

await close()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Closes the connection to Discord.
shrewd fjord
#

Thise ^^^

#

This*

white citrus
shrewd fjord
# white citrus

async def somefunc()
#put the codes from options to options.append
then
asyncio.run(somefunc())

slate swan
shrewd fjord
#

close()

slate swan
#

okay leme try

slate swan
shrewd fjord
#

Noice

tardy lagoon
#

Any have the time to make an anti-raid bot?

slate swan
tardy lagoon
#

I know someone looking for a dev

swift pumice
shrewd fjord
#

Description*

#

Bro i am trippin, it is called "doc strings"

swift pumice
#

Ohh

#

I didnt know

#

Thanks

shrewd fjord
#

Np

tardy lagoon
shrewd fjord
#

Nope, you can use doc strings to describe a command in discord

#

But yeah, it can be used to describe a function too

tardy lagoon
#

Mk, just knew that

shrewd fjord
#

Asher, help me fr πŸ’€

shrewd apex
shrewd fjord
#

Ignore that it's replit

tardy lagoon
#

I typically use

@commands.Bot.command(brief = "short description", description = "long description")
shrewd fjord
#

Tried changing name from .toml and also tried changing the folder name

#

Still same error like bru

shrewd apex
shrewd apex
shrewd fjord
shrewd apex
#

cool

shrewd fjord
#

xd

#

Now help me or πŸ”«

tardy lagoon
shrewd apex
shrewd fjord
#

Asher πŸ—ΏπŸ—ΏπŸ—Ώ

#

Bro fr ignoring

shrewd apex
shrewd fjord
#

This is the error only

shrewd apex
#

did u set the credentials

shrewd fjord
#

Changing name to different like
sra-wrapper, i cant use poetry build

tardy lagoon
shrewd fjord
#

Only the token righ-?

shrewd apex
shrewd fjord
shrewd apex
#

sra is already taken

shrewd fjord
shrewd apex
#

!pypi sra

unkempt canyonBOT
shrewd fjord
shrewd apex
#

what was wrong with sra-wrapper?

shrewd fjord
#

Like wtf dude πŸ’€

shrewd apex
#

send error

shrewd fjord
#

Sec

shrewd fjord
#

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?

shrewd apex
#

in poetry

#

.toml

shrewd fjord
#

pyproject.toml

shrewd apex
#

what is name of project?

shrewd fjord
#

sra

shrewd apex
#

qlso

shrewd fjord
#

Changed it to sra-wrapper

shrewd apex
#

the folder

#

needs to be sra-wrapper

#

the folder containing the code

#

check pokelance

shrewd fjord
shrewd fjord
shrewd apex
#

show ur file structure

shrewd fjord
shrewd apex
#

and show toml file

shrewd fjord
#

Sec

shrewd fjord
#

Why do i think i need to change the repl name fr

shrewd apex
#

its probably replit

shrewd fjord
#

Yeah sec then

shrewd apex
#

make a new repl and clone it ig

shrewd fjord
#

Ugh same error

#

Ig lemme fork

shrewd fjord
#

Dont tell me to copy paste the codes now fr πŸ’€

shrewd apex
#

yeah probably repl does some settings in the back

#

y are u using replit tho use github codespaces no?

shrewd fjord
#

It will be easy to integrate with github

#

From replit it's hard and sometime crashes

shrewd fjord
#

CatLover explained it alr tho

#

You can't do await without async functions

shrewd fjord
#

Got it alr

unkempt mauve
#

about the ban command, how do you check role position?

slate swan
#

!d discord.Role.position

unkempt canyonBOT
#

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.

slate swan
#

!d attribute

unkempt canyonBOT
#

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().

slate swan
#

!d attribute Message

unkempt canyonBOT
#

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().

slate swan
#

Command raised an exception: AttributeError: 'Message' object has no attribute 'create_at'

#

pls help me to fix this error

slate swan
slate swan
#

**pls fix thiss **

#

Command raised an exception: AttributeError: 'Message' object has no attribute 'create_at'

slate swan
slate swan
#

AttributeError: 'Context' object has no attribute 'Message'

#

it's message, not Message

slate swan
#

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

#

this is the code line

#

!d discord.Embed.set_footer

unkempt canyonBOT
#

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.
meager chasm
slate swan
#

@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

slate swan
unkempt canyonBOT
#
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**.
slate swan
#

the embed kwarg

slate swan
slate swan
slate swan
#

how to do it

slate swan
slate swan
# slate swan Here

bro can u pls make a good stats embed code for my bot i am newbie in python

frosty parrot
#

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 ?

vast quarry
#

Hello

#

I have a problem

#

Thar's the problem , so what's the Solution?

peak pilot
peak pilot
vast quarry
#

someone helped me

#

thank u

peak pilot
#

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?

unkempt canyonBOT
#

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!

peak pilot
#

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)`
weary flume
#

how to i put permissions on my slash commands?

white citrus
solemn tree
#

How would i do something like this>

white citrus
# shrewd fjord async def somefunc() #put the codes from options to options.append then async...
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```
steep wedge
#

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

pearl latch
#

@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

slate swan
#

i need hekp with discord-components can someone help me

vestal laurel
#

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)```
velvet compass
#

!code

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

vestal laurel
#

really i jus dk the python code to translate user input, it should work if i can implement it after return str

steep wedge
vestal laurel
#

googletrans recommended translator and i switched to translate in return str

#

idk if it recognizes translate tho

steep wedge
#

you can't just

vestal laurel
#

idrk python yall bare with me

steep wedge
#

put Translator and expect it to work

vestal laurel
white citrus
#

I have some problem with the dropdown

steep wedge
#

Translator isn't anything

steep wedge
vestal laurel
steep wedge
#

also there are other errors but this is the one i'm most concerned about

vestal laurel
#

IDK help a g out

steep wedge
vestal laurel
#

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

steep wedge
#

Translator simply doesn't exist as a thing

vestal laurel
steep wedge
vestal laurel
#
import randfacts
import googletrans
from googletrans import Translator```
vestal laurel
steep wedge
#

have you installed the googletrans module?

vestal laurel
steep wedge
#

ah okay then that should be fine

#

the main problem in that case is the way you're using the decorator

steep wedge
#
@bot.command()
async def translate(ctx, *args):
  #code here```
#

make srue you import discord and discord.ext commands

#

and all that stuff

slate swan
#

help 😦

vestal laurel
#

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```
slate swan
#

@vestal laurel can you help me

vestal laurel
steep wedge
slate swan
#

```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

velvet compass
#

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

steep wedge
slate swan
#

wait so what do i do

steep wedge
#

it actually says that word for word

steep wedge
white citrus
#

Can someone help?

slate swan
#

i need discord-components an nextcord

steep wedge
#

well they are incompatible as it says

#

maybe try updating them idk

#

idk what nextcord actually is haha

velvet compass
slate swan
steep wedge
white citrus
#

Can someone help me please

slate swan
#
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

velvet compass
slate swan
velvet compass
#

I'm sorry I don't have the time right now. I'd suggest making a new venv and install from scratch

vestal laurel
sick birch
# white citrus

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?

white citrus
sick birch
#

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__

sick birch
#

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

slate swan
#
  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)```
sick birch
#

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)

slate swan
#

!d discord.ui.View

unkempt canyonBOT
#

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.
slate swan
#

use Views

sick birch
#

Oh yeah, sorry. Looks like I sent it before I was even done

young dagger
#

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?

keen niche
#

is it against discord TOS to make a bot out of a reg client?

sick birch
civic fractal
lethal bloom
#

important is based on what your bot does

lethal bloom
smoky sinew
#

ok

frosty parrot
#
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

smoky sinew
#

it's a constructor

frosty parrot
#

Ok

raw quail
#

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?

civic fractal
#

you're probably being rate limited

#

but you can check your logs and read the error messages

frosty parrot
#
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'

civic fractal
#

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

frosty parrot
#

it'll give me many errors

#

AttributeError: module 'discord' has no attribute 'contex'

civic fractal
#

it's uppercase

frosty parrot
#

AttributeError: module 'discord' has no attribute 'Context'

unkempt mauve
#

can timeout accept seconds?

frosty parrot
#

yes

unkempt mauve
frosty parrot
unkempt mauve
frosty parrot
#

wait

smoky sinew
frosty parrot
#

I'm sending the full code

smoky sinew
#

this is why i don't send examples with type hints nobody understands what it does

smoky sinew
smoky sinew
frosty parrot
unkempt mauve
#

await timeout(until, /, *, reason=None
What does '/' do?

smoky sinew
unkempt mauve
frosty parrot
#

ok I'm putting .tree in middle of them

unkempt mauve
civic fractal
#

the type hint is not correct though, it should actually be discord.ApplicationContext although most people don't even hint the ctx anyway

smoky sinew
frosty parrot
#

but then the slash command isn't showing

civic fractal
#

bot.command's supply a context parameter

unkempt mauve
civic fractal
#

hence the error message

civic fractal
frosty parrot
civic fractal
#

you've defined a normal textual-prefix command

frosty parrot
#

I send the full code check that

smoky sinew
#

?

#

hybrid commands take regular context too

unkempt mauve
#

the thing is bot.tree.command is not valid slash command registering method but tree.command is

civic fractal
civic fractal
#

I was thinking of pycord

#

I suppose OP is using discord.py so that may not be relevant

unkempt mauve
#

it needs to ctx

#

or context u say

frosty parrot
#

ok

#

wait

smoky sinew
#

i forgot that exists lol

unkempt mauve
#

can someone explain me why '/' exists in the timeout func

frosty parrot
#
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)```
smoky sinew
frosty parrot
#

like this ?

smoky sinew
unkempt mauve
smoky sinew
#

then replace it with interaction

frosty parrot
#

ok

unkempt mauve
#

I dont think bot.tree.command work

smoky sinew
#

it does

unkempt mauve
frosty parrot
smoky sinew
#

hm

unkempt mauve
#

try that

smoky sinew
#

where would tree be defined

frosty parrot
#

I already trien that

smoky sinew
#

!d discord.app_commands.CommandTree.command @unkempt mauve

unkempt canyonBOT
#

@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.
unkempt mauve
#

why mention me smh

smoky sinew
#

sorry, i was just letting you know it does exist

unkempt mauve
#

but I have never saw bot.tree.command register slash cmds

#

When I was a one file dev, I used CommandTree

smoky sinew
frosty parrot
smoky sinew
unkempt mauve
#

what will do about that?

smoky sinew
#

are they not?? i have never used commandtree.command

frosty parrot
#

yea he is right

smoky sinew
#

i think it does register them

frosty parrot
#

it's not showing the slash command

unkempt mauve
smoky sinew
unkempt mauve
#

bot.tree.sync()

smoky sinew
#

just do it inside a message command

unkempt mauve
frosty parrot
#

where to put it ?

unkempt mauve
#

only for you

frosty parrot
#

like ?

smoky sinew
#
@commands.is_owner()
@bot.command()
async def sync(ctx):
    await ctx.send("syncing")
    await bot.tree.sync()
unkempt mauve
frosty parrot
#

ok

frosty parrot
#

after the code ?

smoky sinew
#

i like to use the jishaku sync command

unkempt mauve
#

on_ready event takes time and sometime discord can ratelimit u

unkempt mauve
smoky sinew
frosty parrot
#
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
unkempt mauve
smoky sinew
#

wdym don't prefer syncing?

unkempt mauve
smoky sinew
#

ok

unkempt mauve
#

should the time argument be str or int? (timeout)

#

ik am dumb

smoky sinew
#

i think it's datetime

frosty parrot
#

discord.ext.commands.errors.CommandRegistrationError: The command sync is already an existing command or alias.

smoky sinew
#

read what the error says

unkempt mauve
#

did u put it somewhere as alias?

#

there it is

frosty parrot
unkempt mauve
#

he already put it as cmd

frosty parrot
unkempt mauve
#

it is now one

frosty parrot
#

What !

unkempt mauve
#

btw can u check where u put 'sync' as an alias?

#

it will help u

frosty parrot
#

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

smoky sinew
frosty parrot
smoky sinew
#

it looks like this one is different from the one i sent

smoky sinew
frosty parrot
smoky sinew
#

by removing it

#

how is discord.py supposed to know what command to run if there's multiple commands by the same name

frosty parrot
#

just remove it ?

smoky sinew
#

sure

frosty parrot
#

ok

#

still not working

#

can you please check the code ?

frosty parrot
smoky sinew
#

what's not working

#

i've already looked at the code

unkempt mauve
#

TypeError: unsupported type annotation <class 'datetime.timedelta'>

#

sheesh help

smoky sinew
frosty parrot
smoky sinew
#

have you tried running the sync command...

unkempt mauve
smoky sinew
#

remove the typehint

#

well, there's no time parameter in slash commands anyway

#

so you'll have to convert it manually from a string

unkempt mauve
#

the '/' is the timedelta!?

smoky sinew
#

what.. no

#

i've already told you what the slash does

frosty parrot
unkempt mauve
frosty parrot
#

I mean I tried but same problem

smoky sinew
#

just keep one of them, because you have two sync commands

smoky sinew
# unkempt mauve to me?

yes, the / makes the argument positional, your issue is that you can't have a time parameter with slash commands

frosty parrot
#

after the 3 slash commands I put 1

#

sync command

smoky sinew
frosty parrot
#

other 2 is showing

#

But the embed command isn't showing when I type "/"

smoky sinew
#

it's not going to show if you don't sync

#

also, you shouldn't sync in setup_hook either

frosty parrot
#
    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 ?

smoky sinew
#

no

#

you weren't even using that class to begin with

#

you can remove it if you'd like

frosty parrot
#

so ?

smoky sinew
#

use a sync command

#

i'm not sure what was wrong with your other code

#

but you had two sync commands

frosty parrot
#

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!")

smoky sinew
frosty parrot
smoky sinew
#

it was before

frosty parrot
#

it just not showing the '' command

#

""

smoky sinew
#

that's because you have to use the sync command

#

to sync the commands

fringe pasture
#

how to fix warning unused import

smoky sinew
fringe pasture
smoky sinew
#

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

fringe pasture
#

you think the bot will work without importing discord

smoky sinew
#

yes

fringe pasture
#

thanks

frosty parrot
#

it's not working bro

smoky sinew
frosty parrot
#

and why the add command still showing after deleting the command in code

frosty parrot
smoky sinew
#

you have to communicate with discord servers that the command has been deleted

smoky sinew
#

-sync

frosty parrot
#

ok

#

it's showing now

#

the same command 2 times

frosty parrot
smoky sinew
frosty parrot
#

like 2 hello commands

#

and embed command isn't responding

frosty parrot
#

AttributeError: 'Guild' object has no attribute 'icon_url'

smoky sinew
#

!d discord.Guild.icon

unkempt canyonBOT
frosty parrot
#

and why the add command still sowing ?

fringe pasture
#

do you guys have some simple code to run bot i want to see the different between my code. and yours

smoky sinew
fringe pasture
#

just anything i will see

smoky sinew
#

here is an old bot

fringe pasture
frosty parrot
fringe pasture
fringe pasture
smoky sinew
#

i have a new bot that i haven't committed yet

frosty parrot
#

I got this massive ammount of codehttps://paste.pythondiscord.com/yekehoxilo

woeful magnet
#

Hello, I am developing new discord bot now

marble surge
#

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.

woeful magnet
#

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?

unkempt mauve
#

the bot can only read its dms

woeful magnet
unkempt mauve
woeful magnet
unkempt mauve
#

thats why DM is a safe place

woeful magnet
naive briar
#

No

unkempt mauve
#

Its impossible for the bot to read your DMs

woeful magnet
woeful magnet
civic fractal
#

only DMs between your bot and people who DM your bot
not between you and other people

thorn nova
#

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

frosty parrot
#

discord.app_commands.errors.CommandInvokeError: Command 'embed' raised an exception: AttributeError: 'Guild' object has no attribute 'icon_url'how to fix it ?

naive briar
#

!d discord.Guild.icon

unkempt canyonBOT
naive briar
#

Read the docs

thorn nova
#

I'm keen to setup transcription on my bot, but can't work out how to get a voice channel audio stream...

unkempt mauve
frosty parrot
#
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 ?

brazen raft
#

It's changed from guild.icon_url to guild.icon.url

marsh crypt
#

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

brazen raft
thorn nova
#

Any other way you can think of that I could achieve this?

brazen raft
#

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

thorn nova
#

Yeah was just after the convenience of doing it through a command

brazen raft
#

I commend your dedication

marsh crypt
# brazen raft Sure it can

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

brazen raft
#

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

brazen raft
#

A Discord bot doesn't have to interface with Discord only

marsh crypt
brazen raft
#

But in the case of a calculator, it is. That is unless you use a calculator API online πŸ€”

marsh crypt
#

Hmmm

#

Any examples can I see can it attach to google sheets or excel or Jupiter note books?

brazen raft
#

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

marsh crypt
#

Wow

#

Complexity

marsh crypt
#

That so crazy

#

Mind. If I dm you?

brazen raft
#

Ye, I do mind that. Why do you need to?

raw quail
#

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?

glad cradle
#

he could look at the source of pycord and discordjs since these implement voice receiving

frosty parrot
#
    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 ?
brazen raft
#

If it's undocumented doesn't, it mean it's impossible? How did those libraries even know where to look

frosty parrot
brazen raft
#

Did you load the cog

#

!d discord.ext.commands.Bot.add_cog

unkempt canyonBOT
#

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...
glad cradle
#

and it doesn't even go against Discord's tos

slate swan
#

AttributeError: 'Member' object has no attribute 'avatar_url'

#

i am getting this error

#

pls fix this

naive briar
#

!d discord.Member.avatar

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
naive briar
#

Read the docs

slate swan
#

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 **

vocal snow
#

Presence intents enabled?

slate swan
#

they are enabled

vocal snow
#

In code too?

#

And member intents too?

slate swan
slate swan
vocal snow
#

The same way you enable any other intent

slate swan
#

intents.members = True

#

this is enabled

#

@vocal snow

vocal snow
#

And presences too, you are sure

slate swan
#
intents = Intents.default()
intents.message_content = True
intents.members = True ```
#

these all i enabled

#

@vocal snow

vocal snow
#

Bruh

#

First question was about Presence Intents

#

Why did you say yes lol

slate swan
vocal snow
#

Yes

#

intents.presences

#

You might as well use Intents.all()

slate swan
#

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

tribal pivot
#

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.

tribal pivot
rustic shard
tight sky
#

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.

alpine cove
#

thats not an error

#

return code 0

tight sky
#

forgot to add rest sorry

alpine cove
#

u good

#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

tight sky
#

oh my bad

alpine cove
#

sure that the spotify lib is async?

tight sky
#

yes^

#

well i am using spotipy lib

#

i think i got it to work

#

thanks tho invalid

tribal pivot
#

How do I handle clicking on the button after restarting the bot, and not create a new button?

bronze whale
#

<@&831776746206265384>

bronze whale
tight obsidian
#

hello, what's up?

bronze whale
#

Isn’t that against the rules

#

To bully someone

#

When they trying to help

tight obsidian
#

pithink their name is Invalid

bronze whale
#

OH LMFAO

#

SRY

#

you enjoy your day

#

πŸ™‚

tight obsidian
#

(in either case that word is not used in that meaning nowadays)

bronze whale
#

It means an ill person right?

#

I think

#

But also a insult

tight obsidian
bronze whale
#

Ok

#

Btw

tight obsidian
#

Nowadays it most probably means "not correct"

#

anyway... discord bots

bronze whale
#

@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

final walrus
#

Is there anything more satisfying than watching millions of Django datetime warnings fly past your terminal

bronze whale
#

Anyway wrong channel

final walrus
#

Oh

#

Damn ment to post that in general

tribal pivot
#

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?

naive briar
#

Make it persistent

#

!d discord.Client.add_view

unkempt canyonBOT
#

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.
tribal pivot
final walrus
#

Has anyone here ever turned a discord bot into a Frankenstein server backend with url routing

naive briar
slate swan
#

what is the command line to put the server name in bot's server info command

vocal snow
#

If you have a Guild object you can use .name

slate swan
#

like this ?

#

i have tried this but it shows numbers instead of servername

vocal snow
#

why len()?

naive briar
#

🫠

vocal snow
#

I would recommend reading your code to see what's wrong with it lol

slate swan
#

'NoneType' object has no attribute 'create_webhook' pls fix this

woeful magnet
#

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'

vocal snow
vocal snow
#

And it's giving you an error as you would expect

slate swan
woeful magnet
#

Then I wanna create DM channel in category with received message, how can I achieve that?

vocal snow
vocal snow
#

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

woeful magnet
vocal snow
#

And send a message there if you want

woeful magnet
#

great

slate swan
#

@vocal snowbro i am not getting what u r saying how to fix that attribute error

shrewd fjord
#

!e
print(None.create_webhook)

unkempt canyonBOT
#

@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'
shrewd fjord
#

This ^^^^

slate swan
#

hi im new to python and i want to build a multipurpose bot can some1 help me

shrewd fjord
#

Just drop the problem or wues

slate swan
# shrewd fjord This ^^^^
@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 ?
shrewd fjord
#

Ques*

shrewd fjord
#

Try printing log_channel and u will know

shrewd fjord
slate swan
#

Can someone dm me if they can help me make a discord bot on python plzz

vocal snow
slate swan
#

No I just need to make a bot I'm new to python

#

I'm new to coding actually

vocal snow
#

Best you start with learning python basics first

#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

vocal snow
#

Lots of free courses here; you can filter the results with Beginner difficulty and course/book

slate swan
#

TY

#

I'll maybe come back once I'm more experienced

vocal snow
frosty parrot
#

Does anyone have the code for a music bot ?

vocal snow
#

!ytdl

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

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)
vocal snow
#

(Unless you wanted to make one that plays copyright free music)

woeful magnet
#

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.

slate swan
#
    @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```
naive briar
upbeat otter
upbeat otter
#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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...
slate swan
#

oh.

#

tysm

upbeat otter
#
await interaction.response.defer()

# do stuff

await interaction.edit_original_response(...)
#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

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.
fresh fern
#

`
@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....

naive briar
#

You can't use custom emojis in embed titles

fresh fern
#

help me :(

golden portal
naive briar
#

Never tried that pithink

golden portal
#

hehe yea embeds are rly weird on which fields gets to use it

#

it needs to be <:emoji name:emoji id> format

slate swan
#

id

tribal pivot
#

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)
rare echo
#

you need the id

tribal pivot
rare echo
#

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 pithink

golden portal
tribal pivot
golden portal
# tribal pivot 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

fresh fern
#

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

naive briar
#

Why is the a there

golden portal
#

welcome :>

fresh fern
#

help me 🀧🀧

naive briar
#

Invalid format

#

Read the docs

fresh fern
#

please......

#

iam*

#

the has_permissions is not working

#

it doesnt check if the user got perms or not

#

hmm

white citrus
#

I dont get it rng

fresh fern
#

@slate swan

#

im using the same and its not working

naive briar
#

What

fresh fern
#

i dont have any problem in banning

white citrus
unkempt mauve
#

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?

naive briar
#

!d discord.Client.add_view

unkempt canyonBOT
#

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.
unkempt mauve
unkempt canyonBOT
#

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())```
unkempt mauve
#

Will it last even if I restart the bot?

naive briar
#

Did you read the embed

#

Then you'll know the answer

unkempt mauve
slate swan
#

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

wanton pebble
#

am i able to use wait for message in the on message event?

naive briar
#

Why not

wanton pebble
#

it says i cant use await outside a function

white citrus
#

how can i check in which cog is an application subcommand?

wanton pebble
#

cant you just click on ur cogs and ctrl f it?

white citrus
#

it is for a command list

naive briar
wanton pebble
unkempt mauve
#

how do I make these commands guild_only?

golden portal
unkempt canyonBOT
#

@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...
unkempt mauve
golden portal
unkempt mauve
golden portal
unkempt mauve
#

how do I check if a slash command was ran in a dm?

naive briar
#

!d discord.Interaction.guild

unkempt canyonBOT
naive briar
#

This property will be None

unkempt mauve
slate swan
#

yes

slate swan
unkempt mauve
slate swan
#
AttributeError: 'NoneType' object has no attribute 'create_webhook'```
#

@unkempt mauvecan u fix this bro

#

i am irritated with attributes error

slate swan
#

idk its not in my code but still showing this

unkempt mauve
unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

unkempt mauve
slate swan
#

here it is

#

@unkempt mauvehave u got the fix ?

#

discord api channel? for bots

unkempt mauve
slate swan
unkempt mauve
slate swan
unkempt mauve
#

I meant when it happens?

#

after running code?

#

or after running cmd?

slate swan
#

noo it cames after running cmd -antinuke

unkempt mauve
#

is 'log_channel' defined?

slate swan
velvet compass
#

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

unkempt mauve
#

!d discord.TextChannel.create_webhook

unkempt canyonBOT
#

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.
slate swan
velvet compass
slate swan
#

@velvet compassstill not fixed bro

#

again showing same error

velvet compass
#

If it showed None, then you know the issue is in this line: log_channel = discord.utils.get(ctx.guild.channels, name='audit-log')

slate swan
#

yo can someone help me?

shell wing
#

Don't ask to ask πŸ’€

slate swan
#

?

slate swan
#

im on vscode and im doing python bot.py and my bot is still offine

velvet compass
slate swan
#

ok

shell wing
#

and share the error

white citrus
shell wing
#

not just the issue

slate swan
shell wing
slate swan
white citrus
velvet compass
slate swan
shell wing
white citrus
velvet compass
slate swan
#

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

velvet compass
#

And there is nothing before that?

slate swan
velvet compass
#

Hmm

slate swan
#

its login status

#

before that

velvet compass
#

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

slate swan
#

:/

slate swan
velvet compass
#

logging.warning(f"{log_channel = }") instead of the print

slate swan
#

hm letme check

velvet compass
#

Which will show in the log messages what the value of log_channel is at that point

tough lance
#

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?
velvet compass
#

If it is None, then you will need to address the line above

slate swan
#

does my code llok ok?

#

so far

#

im tryna start it and it dont go online

velvet compass
velvet compass
#

Go ahead and reset that as soon as you can

slate swan
#

ill cover it

velvet compass
slate swan
velvet compass
#

Then how can you get it

#

You need to create it instead

slate swan
#

@velvet compass now? ok

#

can u give a code from which bot will automatically create logs channel

#

@velvet compass

velvet compass
strong crow
velvet compass
slate swan
slate swan
slate swan
#

@velvet compassthat error got fixed but it is coming with new error -_-

quick gust
#

pretty self explanatory

#

youre doing self= but not giving it a value

slate swan
quick gust
#

nothing

#

you remove the self=

slate swan
vital glacier
#

How do I get the amount of commands in a cog file? (This is for a subclassed help command)

quick gust
slate swan
#

when i run py bot.py the cmd bit disappears and i need to create a new terminal pls help7

slate swan
#
@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

fallow mauve
#

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 ._.

quick gust
unkempt canyonBOT
#

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.
quick gust
quick gust
#

you use ctx.guild