#discord-bots

1 messages · Page 530 of 1

slate swan
#

Good

steep estuary
#

also i used it once and i was showing ffmpeg error

#

but now that is fixed :)

slate swan
#

Read it please

steep estuary
#

ok

boreal ravine
#

he said should i use youtube_Dl ? he didnt say he was gonna use it

hasty iron
#

the answer is no

boreal ravine
#

yes

steep estuary
#

then what should i use?

#

for play command ?

boreal ravine
#

idk

#

playing youtube is illegal

steep estuary
#

ohh

#

what skyra and probot use to play?

#

is there any legal way?

boreal ravine
#

im not youtube

#

🗿 👍

steep estuary
#

:/

slate swan
steep estuary
#

what?

slate swan
#

Why do you think YouTube shuts down music bots

#

Might want to reconsider if you really want to make a music bot

steep estuary
#

:/

#

ok

#

then wht about skyra?

#

it also plays music

hasty iron
#

you can play your own music

#

and ncs

steep estuary
#

from system files?

slate swan
#

Yes

#

Without streaming from YouTube

steep estuary
#

i cannot download all music in pc

#

:/

slate swan
#

Then don't make a music bot

steep estuary
#

ok :((((((((((

harsh cradle
#

i have level system

#

with sqlite3 and i wanna make give level command

hasty iron
#

then make it

junior verge
#
import discord
from discord.ext import commands

class Dm(commands.Cog):
    def __init__(self, client):
        self.client = client


    @commands.Cog.listener()
    async def dm(ctx):
        await ctx.send("**DM me with your question to create a ticket!**")

def setup(client):
    client.add_cog(Dm(client))
#

How doesn't this work?

boreal ravine
#

just remove the event and replace it with commands.command()

junior verge
#
import discord
from discord.ext import commands

class Dm(commands.Cog):
    def __init__(self, client):
        self.client = client


    @commands.Cog.command()
    async def dm(ctx):
        await ctx.send("**DM me with your question to create a ticket!**")

def setup(client):
    client.add_cog(Dm(client))
``` Not like this right
junior verge
#

uhm

#

I think I am dumb

slate swan
#

Python understanding NotLikeThis

#

Remove the Cog part

junior verge
#

oh..

boreal ravine
slate swan
#

and add self in the parameters list

#

before ctx

junior verge
#

Okay

#

Also I got like a big problem with my modmail system, literally every message that I send in my server creates a modmail, it only needs to be when I dm my bot with a question which it does.

#
import discord
from discord.ext import commands
from datetime import datetime

class Member(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author == self.client.user:
            return
        else:
            guild = self.client.get_guild(867086205182017536)
            channels = await guild.fetch_channels()
            channel = discord.utils.get(channels, name = str(message.author.id))


            if channel is None:
                category = discord.utils.get(guild.categories, name = "Tickets")
                channel = await guild.create_text_channel((message.author.name),category = category)
                await message.author.send("Modmail has been created succesfully")
                em = discord.Embed(
                    title = f"{message.author.name}#{message.author.discriminator} created a modmail",
                    description = {message.content},
                    timestamp = datetime.utcnow(),
                    color = discord.Color.dark_blue()
                )
                await channel.send(embed = em)

            else:
                em = discord.Embed(
                    title = f"{message.author.name}#{message.author.discriminator}",
                    description = {message.content},
                    timestamp = datetime.utcnow(),
                    color = discord.Color.dark_blue()
                )
                await channel.send(embed = em)

def setup(client):
    client.add_cog(Member(client))
slate swan
#

Don't check every message then

junior verge
#

How?

slate swan
#

Check if the channel is a private message channel

#

Yeah like that

#

So many spaces NotLikeThis

junior verge
#

It's clean though

junior verge
slate swan
boreal ravine
slate swan
#

*at

boreal ravine
#

btw why do u have an else statement

slate swan
#

KryptonThink Do you even know how the library or Python works

odd pendant
slate swan
junior verge
#

Why are you guys just trying to make fun of me

slate swan
#

have you coded this by yourself

odd pendant
#

we're not we're pointing out things

junior verge
odd pendant
#

well what is wrong with this? py if channel is None: em = ... await channel.send(embed = em)

boreal ravine
odd pendant
#

you can't send an embed to something that is None

#

so thats not needed

junior verge
#

Yeah I see that it's not needed

slate swan
#

Not "not needed"

#

Maybe you need it

junior verge
slate swan
#

But implemented it in a wrong way

#

Just change it and check if the channel is a DMChannel

#

Since that's what you want to do

junior verge
#

Yeah

slate swan
junior verge
#

That works, but my respond system and close system doesn't work as well

#

Yeah that works

#
import discord 
from discord.ext import commands
from datetime import datetime

class Mod(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_message(self, message):
        try:
            if ".close" in message.content:
                pass
        
            else:
                if str(message.channel.type) == "private":
                    return
                else:
                    if message.author == self.client.user:
                        return
                    else:
                        user = await message.guild.fetch_member(int(message.channel.name))
                        emb = discord.Embed(
                            title = "Message from the staff team",
                            description = {message.content},
                            timestamp = datetime.utcnow(),
                            color = discord.Color.green()
                        )
                        await user.send(embed = emb)
        except Exception as e:
            print(e)
            pass

    @commands.command()
    async def close(self, ctx):
            user = await ctx.guild.fetch_member(int(ctx.channel.name))
            await user.send("The modmail has been closed by the staff team")
            await ctx.channel.delete

def setup(client):
    client.add_cog(Mod(client))
odd pendant
#
channels = await guild.fetch_channels()
channel = discord.utils.get(channels, name = str(message.author.id))```
can be changed to ```py
channel = discord.utils.get(guild.channels, name=str(message.author.id))```
#

and user = await message.guild.fetch_member(int(message.channel.name)) can be changed to user = message.guild.get_member(int(message.channel.name))

junior verge
#

Then it says message is not defined

odd pendant
#

oh i was talking about the on_message, if you mean for the command use ctx instead of message

junior verge
#

ah

odd pendant
#

ctx.guild.get_member

junior verge
#

Yeah

#

But you got any idea how to fix it that it sends the response in dms back and closes the ticket on .close which it doesn't

odd pendant
#

what do you mean? all the messages you send are to the user

junior verge
#

When I am in the channel that has been created by the bot, when I should say for example: "test" it should send that back in dms to the person

#

which it doesn't

odd pendant
#

could you show your updated code please

junior verge
#

sure

#
import discord 
from discord.ext import commands
from datetime import datetime

class Mod(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_message(self, message):
        try:
            if ".close" in message.content:
                pass
        
            else:
                if str(message.channel.type) == "private":
                    return
                else:
                    if message.author == self.client.user:
                        return
                    else:
                        user = await message.guild.fetch_member(int(message.channel.name))
                        emb = discord.Embed(
                            title = "Message from the staff team",
                            description = {message.content},
                            timestamp = datetime.utcnow(),
                            color = discord.Color.green()
                        )
                        await user.send(embed = emb)
        except Exception as e:
            print(e)
            pass

    @commands.command()
    async def close(self, ctx):
            user = await ctx.guild.fetch_member(int(ctx.channel.name))
            await user.send("The modmail has been closed by the staff team")
            await ctx.channel.delete

def setup(client):
    client.add_cog(Mod(client))
odd pendant
#

{message.content} can just be message.content

junior verge
#

Yeah I just noticed that as well

odd pendant
#

thats not the problem though

junior verge
#

No I know

odd pendant
#

maybe remove the try and except and see if anything gets raised

#

i can't see anything wrong with it

junior verge
#

Yeah

odd pendant
#

apart from you shouldn't be fetching the members unless you really have to

#

you should be using guild.get_member

#

which isn't a coroutine btw

junior verge
#

Okay

slate swan
#

Also

#

Taking in consideration you previously created channels based on the username and not the ID

#

Nevermind

junior verge
#

What about it?

slate swan
#

I can't read

junior verge
#

lol

boreal ravine
#

coroutines are funny

#

await guild.get_member() 🗿 😂

reef shell
#

It's not a coro

#

iirc

junior verge
#

alr but

#

anyone got a fix maybe?

slate swan
#

What is your current edited code

junior verge
#
import discord 
from discord.ext import commands
from datetime import datetime

class Mod(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_message(self, message):
        try:
            if ".close" in message.content:
                pass
        
            else:
                if str(message.channel.type) == "private":
                    return
                else:
                    if message.author == self.client.user:
                        return
                    else:
                        user = await message.guild.fetch_member(int(message.channel.name))
                        emb = discord.Embed(
                            title = "Message from the staff team",
                            description = message.content,
                            timestamp = datetime.utcnow(),
                            color = discord.Color.green()
                        )
                        await user.send(embed = emb)
        except Exception as e:
            print(e)
            pass

    @commands.command()
    async def close(self, ctx):
            user = await ctx.guild.fetch_member(int(ctx.channel.name))
            await user.send("The modmail has been closed by the staff team")
            await ctx.channel.delete

def setup(client):
    client.add_cog(Mod(client))
``` this atm
boreal ravine
#

fix for?

slate swan
#

Now what doens't work

junior verge
#

Sending the embed back to the user in dms once I send the message in the created channel

boreal ravine
junior verge
#

When I type a message in the the channel nothing happens

slate swan
#

Do you have errors?

junior verge
#

Nope

slate swan
#

Also, you shouldn't always use fetch_member

#

Use get_member and then fetch_member if it returned None

boreal ravine
slate swan
#

Example here

junior verge
boreal ravine
slate swan
#

And

await ctx.channel.delete

should be changed to

await ctx.channel.delete()

because it's a method and not an attribute

junior verge
boreal ravine
#

!d discord.TextChannel.type

unkempt canyonBOT
boreal ravine
#

hm

slate swan
#

You should check if the channel is an instance of DMChannel

junior verge
#

How?

slate swan
#

Have you tried adding random print statements to see how your code flows

junior verge
#

Nope I'll do that now

slate swan
#

Yeah you should

junior verge
#

Done

#

It prints 1 1 1 then it prints 5

#
import discord 
from discord.ext import commands
from datetime import datetime

class Mod(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_message(self, message):
        try:
            print(1)
            if ".close" in message.content:
                pass
                print(2)
            else:
                if str(message.channel.type) == "private":
                    return
                    print(3)
                else:
                    if message.author == self.client.user:
                        return
                        print(4)
                    else:
                        print(5)
                        user = await message.guild.fetch_member(int(message.channel.name))
                        emb = discord.Embed(
                            title = "Message from the staff team",
                            description = message.content,
                            timestamp = datetime.utcnow(),
                            color = discord.Color.green()
                        )
                        await user.send(embed = emb)
                        print(6)
        except Exception as e:
            print(e)
            pass

    @commands.command()
    async def close(self, ctx):
            user = await ctx.guild.fetch_member(int(ctx.channel.name))
            await user.send("The modmail has been closed by the staff team")
            await ctx.channel.delete()
            print(7)

def setup(client):
    client.add_cog(Mod(client))
boreal ravine
#

hm

junior verge
#

any clue

slate swan
#
import requests
import discord
from discord.ext import commands

import config
 
bot = commands.Bot(command_prefix=".", intents=discord.Intents.all())
 
 
@bot.event
async def on_ready():
    print("Bot connected")
 
 
@bot.command()
async def join(ctx):
    """target_application_id
 
        Youtube Together - 755600276941176913
        Betrayal.io - 773336526917861400
        Fishington.io - 814288819477020702
        Poker Night - 755827207812677713
        Chess - 832012774040141894
 
    """
 
    data = {
        "max_age": 86400,
        "max_uses": 1,
        "target_application_id": 755600276941176913, # YouTube Together
        "target_type": 2,
        "temporary": False,
        "validate": None
    }
    headers = {
        "Authorization": "Bot token",
        "Content-Type": "application/json"
    }
 
    if ctx.author.voice is not None:
        if ctx.author.voice.channel is not None:
            channel = ctx.author.voice.channel.id
        else:
            await ctx.send("Зайдите в канал")
    else:
        await ctx.send("Зайдите в канал")
 
    response = requests.post(f"https://discord.com/api/v8/channels/{channel}/invites", data=json.dumps(data), headers=headers)
    link = json.loads(response.content)
 
    await ctx.send(f"https://discord.com/invite/{link['code']}")
 
bot.run(config.TOKEN)```
fathom hamlet
#

Hi, I'm new to Python and started learning a few weeks ago. I'm trying to create a very simple discord bot with just one command as of now. And I'm having trouble making the env file for the token. It's responding with this.

AttributeError: 'NoneType' object has no attribute 'strip'

Does anyone know what I can do to fix this? I can even send my code or whatever here.

junior verge
fathom hamlet
junior verge
#

Can you send your code?

slate swan
#

i created a bot using python

junior verge
#

nice

fathom hamlet
# junior verge Can you send your code?

import discord
import os
client = discord.Client()

@client.event
async def on_ready():
print('We have logged in as {0.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
message.channel.send('Hello!')

client.run(os.getenv('TOKEN'))

junior verge
#

Make sure to use ```py

visual island
reef shell
#

await message.channel.send("ldkjfkl") in last line

slate swan
#

yes

fathom hamlet
junior verge
#

What do you got in your env?

fathom hamlet
reef shell
#

should be without spaces

fathom hamlet
#

alr lemme try

slate swan
#

Are you sure the v8 of the API supports watch together?

#

You should try with v9 aka the latest

fathom hamlet
reef shell
#

!code

unkempt canyonBOT
#

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.

slate swan
#

ye

fathom hamlet
#
import discord
import os 
client = discord.Client()

@client.event 
async def on_ready():
 print('We have logged in as {0.user}')
@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith('$hello'):
     message.channel.send('Hello!') 


client.run(os.getenv('TOKEN')) 
#

@reef shell

slate swan
slate swan
#

!indent

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

reef shell
#

I think you did something wrong in the .env file

fathom hamlet
slate swan
#

Well

junior verge
#

Can you send your env file with like black your token

slate swan
#

That's not how to load env files

visual island
slate swan
#

@fathom hamlet take this ```import discord
from discord.ext import commands

bot = commands.Bot(command_prefix=".")

@bot.event
async def on_ready():
print("Bot connected")

@bot.command()
async def hello(ctx):
await ctx.send("hello")

bot.run("token")```

junior verge
#

Can you import discord.ext

slate swan
#

I'm pretty sure os.getenv works for system environment variables, and not .env files

junior verge
#

Isn't the fix just to import disocrd.ext

fathom hamlet
slate swan
reef shell
#

yeah i use dotenv

fathom hamlet
junior verge
fathom hamlet
junior verge
#

My code still does not work to send the embed back in dms

import discord 
from discord.ext import commands
from datetime import datetime

class Mod(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_message(self, message):
        try:
            print(1)
            if ".close" in message.content:
                pass
                print(2)
            else:
                if str(message.channel.type) == "private":
                    return
                    print(3)
                else:
                    if message.author == self.client.user:
                        return
                        print(4)
                    else:
                        print(5)
                        user = await message.guild.fetch_member(int(message.channel.name))
                        emb = discord.Embed(
                            title = "Message from the staff team",
                            description = message.content,
                            timestamp = datetime.utcnow(),
                            color = discord.Color.green()
                        )
                        await user.send(embed = emb)
                        print(6)
        except Exception as e:
            print(e)
            pass

    @commands.command()
    async def close(self, ctx):
            user = await ctx.guild.fetch_member(int(ctx.channel.name))
            await user.send("The modmail has been closed by the staff team")
            await ctx.channel.delete()
            print(7)

def setup(client):
    client.add_cog(Mod(client))
slate swan
marble pilot
#

oh shit

#

srry didnt want to ping

wooden frigate
#

nah i did that cause i like pings

marble pilot
#

LOL

#

lolz oki

#

have a good one

fathom hamlet
marble pilot
#

yeah

#

it is pointless

fathom hamlet
#

alr lemme try

marble pilot
#

look:

fathom hamlet
#

now it's saying
AttributeError: 'Client' object has no attribute 'command'

marble pilot
#

@wooden frigate
async def hello(ctx):
await ctx.send("hello")

#

from discord import commands

marble pilot
#

and client = commands.Client()

#

LMAO

wooden frigate
marble pilot
#

ye

#

srry my bad

#

^^ command.Bot()

marble pilot
wooden frigate
#

Sorry:
I simplify errors

marble pilot
#

oki

scarlet lava
#

hey, is any of you familiar with Pterodactyl? having a bit of an issue

marble pilot
#

good interpretter

#

whats ur issue

scarlet lava
#

wanna pull from a private repo, but the current setup requires a bot start file (like src/main.py) which is gonna be available after pulling

#

and I feel like the pull is not taking place

#

not sure though

marble pilot
#

hm

#

I am not rlly sure if its releated with #discord-bots but ig i need some photos to understand

#

maybe this will help you out

#

If not then contact me in DM's i guess so we will not break any convo

fathom hamlet
pliant gulch
#

If it requires you to first have a file you can just quickly write a temp file which uses subprocess open I'd assume to run the command

#

!d subprocess.Popen

unkempt canyonBOT
#
class subprocess.Popen(args, bufsize=- 1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, ...)```
Execute a child program in a new process. On POSIX, the class uses [`os.execvpe()`](https://docs.python.org/3/library/os.html#os.execvpe "os.execvpe")-like behavior to execute the child program. On Windows, the class uses the Windows `CreateProcess()` function. The arguments to [`Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen "subprocess.Popen") are as follows.

*args* should be a sequence of program arguments or else a single string or [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object). By default, the program to execute is the first item in *args* if *args* is a sequence. If *args* is a string, the interpretation is platform-dependent and described below. See the *shell* and *executable* arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass *args* as a sequence.
gloomy quest
#

how to add roles to a member

boreal ravine
unkempt canyonBOT
#

await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
gloomy quest
boreal ravine
gloomy quest
#

ooo

boreal ravine
#

i mean u gotta define what role is first

pliant gulch
#

*roles means you can pass a list however many discord.Role instances you want

gloomy quest
#

ooooh

pliant gulch
#

Sorry I mean't you can pass however many roles you want

#

Not in a list *

#

However if you want to bulk add roles it would be better to do Member.edit

gloomy quest
#
await add_roles(discord.roles.id=RoleID, reason=None, atomic=True)```
hexed glade
#

Hello friends ,
I'm trying to build a bot that plays music in the voice chat for some friends. I followed a tutorial and fell into some issues with FFmpeg. I have added it to my path so that windows can now access it and convert the audio , but I don't
hear anything from the bot in chat even though its icon is glowing to show its playing. Any help or ideas mates?

boreal ravine
hexed glade
#

checked. both the system and the bot volume is up

#

thank you !

gloomy quest
#

hm

scarlet lava
#

but thanks for your suggestion :)

pliant gulch
#

If it prompted for your username and access token then it is pulling

scarlet lava
#

i mean i have fields for that in the startup section

pliant gulch
#

Are you able to pass those in?

#

Anyhow seems like you fixed it?

slate swan
#

I want to learn an easy web scraping tutorial, where can I learn it so that I can send the data through my discord bot

cloud dawn
#

Not really a discord bot related task.

shut axle
#
@client.command()
async def join(ctx):
  if (ctx.author.voice):
    channel = ctx.message.author.voice.channel
    voice = await channel.connect()
    source = FFmpegPCMAudio('WOW Anime.mp3')
    player = voice.play(source)
  else:
    await ctx.send(f"{ctx.author.mention}, **You aren't in a voice channel!**")

Why it doesn't play the audio? NO errors..

cloud dawn
#

I suggest not copying code off of the internet.

shut axle
#

I did it in my self

#

damn

stark bobcat
#

hlo

#

ctx.author.activity

#

why doesn't this work

cloud dawn
stark bobcat
#

cause it says status is None

cloud dawn
shut axle
#

I removed it and it doesn't work again... @cloud dawn

cloud dawn
stark bobcat
#

i tried it

maiden fable
#

!d discord.VoiceChannel.connect @shut axle

unkempt canyonBOT
#

await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.

This requires [`Intents.voice_states`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
boreal ravine
#

@stark bobcat does ur bot have member intents?

#

it cant access the members status without them lol

shut axle
maiden fable
#

!d discord.VoiceClient.play

unkempt canyonBOT
#

play(source, *, after=None)```
Plays an [`AudioSource`](https://discordpy.readthedocs.io/en/master/api.html#discord.AudioSource "discord.AudioSource").

The finalizer, `after` is called after the source has been exhausted or an error occurred.

If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be displayed as if it were raised.
shut axle
cloud dawn
#

Throw even more docs lol, fact is that voiceclient is not the nicest class

junior verge
#

My code still does not work to send the embed back in dms

import discord 
from discord.ext import commands
from datetime import datetime

class Mod(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_message(self, message):
        try:
            print(1)
            if ".close" in message.content:
                pass
                print(2)
            else:
                if str(message.channel.type) == "private":
                    return
                    print(3)
                else:
                    if message.author == self.client.user:
                        return
                        print(4)
                    else:
                        print(5)
                        user = await message.guild.fetch_member(int(message.channel.name))
                        emb = discord.Embed(
                            title = "Message from the staff team",
                            description = message.content,
                            timestamp = datetime.utcnow(),
                            color = discord.Color.green()
                        )
                        await user.send(embed = emb)
                        print(6)
        except Exception as e:
            print(e)
            pass

    @commands.command()
    async def close(self, ctx):
            user = await ctx.guild.fetch_member(int(ctx.channel.name))
            await user.send("The modmail has been closed by the staff team")
            await ctx.channel.delete()
            print(7)

def setup(client):
    client.add_cog(Mod(client))```
maiden fable
#

Weird, that should have worked tbh

junior verge
#

Yeah

cloud dawn
#

I suggest getting to know python a bit more before moving to music.

junior verge
#

Me?

cloud dawn
junior verge
#

Ah nah

#

But do you got any idea for mine

cloud dawn
#

Well other than the fact that it's an on_message command bot. Provide some more info, what print does it stop at, errors, intents etc

junior verge
#

When I am trying to send the message back to the user in dms in the created channel from the ticket, it just doesn't do anything

cloud dawn
#

Well that is true because you are getting a user with the channel name? user = await message.guild.fetch_member(int(message.channel.name))

#

Why are you getting the member if you can just do message.author.send()

junior verge
#

How would I write that?

cloud dawn
#

Also this should give an base 10 error convert str to int.

stark bobcat
#

it works now

boreal ravine
#

Nice

stark bobcat
junior verge
#

Nevermind

cloud dawn
junior verge
#

I fixed it already

junior verge
cloud dawn
junior verge
#

Here?

#

Change str to int

#

@cloud dawn Also, what is the name for the person that sends the .close command?

cloud dawn
junior verge
#

yeah

cloud dawn
junior verge
#

Okay

cloud dawn
#

pretty sure the name is not in binary

junior verge
#

I fixed it already that is fine

#

I am just asking what the name would be of the person that sends the response

cloud dawn
#

Then it should be fine right

junior verge
cloud dawn
junior verge
#

I am trying to get here the name of the person that responded in the ticket

slate swan
#

Forgot to add f before the ""

junior verge
#

then it says ctx is not defined

#

nvm

junior verge
#

I get a error if I define ctx

slate swan
#

What is your code

#

I can't guess what's wrong sorry

junior verge
#

All good

slate swan
#

message.author

#

¯_(ツ)_/¯

junior verge
#

aahh

#

cheers 😛

verbal storm
ionic wadi
#
@tasks.loop(seconds=5)
async def my_brain_outdated():
    await bot.change_presence(activity=discord.Game(name="Join de group!"))
    await asyncio.sleep(5)
    await bot.change_presence(activity=discord.Game(name="!help voor de commands!"))
    await asyncio.sleep(5)
    await bot.change_presence(activity=discord.Game(name="Colza Productions"))
    ```

NoneType has no attribute change presence,
A friend of me said the bot Is not defined. But It Is.
junior verge
#

@slate swan When I send the 2nd message back to the bot in dms it writes the message in {''} why is that?

slate swan
#

Again, what's your code

junior verge
#
import discord 
from discord.ext import commands
from datetime import datetime

class Mod(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_message(self, message):
        try:
            print(1)
            if ".close" in message.content:
                pass
                print(2)
            else:
                if str(message.channel.type) == "private":
                    return
                    print(3)
                else:
                    if message.author == self.client.user:
                        return
                        print(4)
                    else:
                        print(5)
                        user = await message.guild.fetch_member(int(message.channel.name))
                        emb = discord.Embed(
                            title = f"{message.author}'s response!",
                            description = message.content,
                            timestamp = datetime.utcnow(),
                            color = discord.Color.green()
                        )
                        await user.send(embed = emb)
                        print(6)
        except Exception as e:
            print(e)
            pass

    @commands.command()
    async def close(self, ctx):
            user = await ctx.guild.fetch_member(int(ctx.channel.name))
            await user.send("The modmail has been closed by the staff team!")
            await ctx.channel.delete()
            print(7)

def setup(client):
    client.add_cog(Mod(client))
slate swan
#

Not this one

junior verge
#
import discord
from discord.ext import commands
from datetime import datetime

class Member(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author == self.client.user:
            return
        if not isinstance( message.channel , discord.DMChannel):
            return
        else:
            guild = self.client.get_guild(867086205182017536)
            channel = discord.utils.get(guild.channels, name=str(message.author.id))


            if channel is None:
                category = discord.utils.get(guild.categories, name = "Tickets")
                channel = await guild.create_text_channel((message.author.id),category = category)
                await message.author.send("Modmail has been created succesfully")
                em = discord.Embed(
                    title = f"{message.author.name}#{message.author.discriminator} created a modmail",
                    description = message.content,
                    timestamp = datetime.utcnow(),
                    color = discord.Color.dark_blue()
                )
                await channel.send(embed = em)
                await channel.send("<@&868232863592620072>")

            else:
                em = discord.Embed(
                    title = f"{message.author.name}#{message.author.discriminator}",
                    description = {message.content},
                    timestamp = datetime.utcnow(),
                    color = discord.Color.dark_blue()
                )
                await channel.send(embed = em)

def setup(client):
    client.add_cog(Member(client))
#

yep

slate swan
#

See by yourself

junior verge
#

sorry :/

slate swan
#

No problem :P

waxen granite
#

how can i get a count of all the commands i have in my bot?

slate swan
#

bot.commands returns a set of all commands

#

So get it's length

junior verge
#

What's wrong here

waxen granite
#

what is the difference between bot.commands and bot.all_commands?

waxen granite
junior verge
#
                    title = f"{message.author.name}#{message.author.discriminator} - f"<@{message.author.id}>" created a modmail",
waxen granite
#

and u havent closed the 1st fstring

junior verge
#

How do I?

#

nvm

waxen granite
junior verge
#

thanks mate

#

It does not ping the person

#

How would I do that in the description?\

slate swan
#

.mention

junior verge
#

?

slate swan
#

message.author.mention

#

¯_(ツ)_/¯

junior verge
#

I mean.

#
                 description = message.content - <@{message.author.id}>,
``` Like how do I do both in the description
slate swan
#

Put everything in a f-string

#

and add curly brackets to message.content

#

!f-strings

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

junior verge
#
description = f"{message.content}" f"{<@{message.author.id}>}",
#

Like that?

slate swan
#

make it only one

junior verge
#

for the 2nd one?

slate swan
#

You don't need to always add the f when you want to put a variable in it

#

Just once in the front and then you can use {} for any variable

slate swan
junior verge
#

ah

junior verge
#
description = f"{message.content}" f"<@{message.author.id}>",
slate swan
#

Without the f

waxen granite
#

its same

slate swan
#

One. single. string.

#

With an f at the beginning

#

That's it

junior verge
#
description = f"{message.content} <@{message.author.id}>",
#

Like that

slate swan
#

Yes

junior verge
#
import discord
from discord.ext import commands

class ping(commands.Cog):
    def __init__(self, client):
        self.client = client

        @commands.Cog.Listener()
        @commands.command()
        async def ping(self, ctx):
            await ctx.reply(f'**Pong!** {round(client.latency * 1000)}ms')



def setup(client):
    client.add_cog(ping(client))
``` What does the @commands.cog.listener needs to be I can't remember
slate swan
#

listener not capital

junior verge
final iron
slate swan
#

just lowercase

#

oh damn

junior verge
#

@commands.Cog.listener()

final iron
#

Yes

junior verge
#

Let's see if it works

#
import discord
from discord.ext import commands

class ping(commands.Cog):
    def __init__(self, client):
        self.client = client
        
        @commands.command()
        async def ping(self, ctx):
            await ctx.reply(f'**Pong!** {round(client.latency * 1000)}ms')



def setup(client):
    client.add_cog(ping(client))
slate swan
#

Indentation

#

Not it's indented inside the __init__

#

why both class name and command name ping

#

Take it out of that

#

And add uppercase to class names

junior verge
#

okay

slate swan
#

that's the convention

junior verge
#

Yeah

#

still error

#
import discord
from discord.ext import commands

class Ping(commands.Cog):
    def __init__(self, client):
        self.client = client

        @commands.command()
        async def ping(self, ctx):
            await ctx.reply(f'**Pong!** {round(client.latency * 1000)}ms')



def setup(client):
    client.add_cog(Ping(client))
slate swan
#

As I said

#

Take the command out of the __init__

junior verge
#
import discord
from discord.ext import commands

class Ping(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    async def ping(self, ctx):
        await ctx.reply(f'**Pong!** {round(client.latency * 1000)}ms')



def setup(client):
    client.add_cog(Ping(client))
slate swan
#

Yes

junior verge
#

Like that?

#

client is not defined

vocal plover
#

its self.client

slate swan
#

Ah well yeah

junior verge
#

On what line?

vocal plover
#

what line does the error say

slate swan
#

Where the errors tells you

junior verge
#

10

slate swan
#

Then go there

junior verge
#

the await ctx.reply

#

aah fixed

slate swan
#

And look where you used client

cinder horizon
#

is it possible to run a cog with a different prefix....like ik dis stoopid but i want the music commands to be run only wid >....plausible?

vocal plover
#

not really, no

#

unless you do your own command parsing within a cog

junior verge
#
import discord
from discord.ext import commands
import nextcord
import nextcord.ext


class Disable(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    async def toggle(ctx, *, command):
        command = client.get_command(command)
        if command == None:
            await ctx.send("Couldn't find that command")
        elif ctx.command == command:
            await ctx.send("You cannot disable this command")
        else:
            command.enabled = not command.enabled
            ternary = "enabled" if command.enabled else "disabled"
            await ctx.send(f'command {command.qualified_name} has been {ternary}')


def setup(client):
    client.add_cog(Disable(client))
``` How would I fix this?
slate swan
#

Fix this, fix what exactly?

junior verge
#

Sorry yeah.

#

It says that client is not defined

slate swan
#

Add self in the command parameters

junior verge
#

still

slate swan
#

and again, replace client with self.client

#

In cogs it's always self.client

junior verge
#

okay

#

Thanks

#

Let's see if it works

slate swan
#

No problem

junior verge
#

Thanks bro, it works.

#

Sorry that I ask a lot.

slate swan
#

It's okay :p

#

I also questioned a lot when I started :)

boreal ravine
#

@slate swan do you actually pay for winrar?

junior verge
#

wait

#

a tab at the @commands.has_permission right

boreal ravine
#

no

junior verge
#

oh :/

boreal ravine
#

put the check above async

junior verge
#

oh shoot I forgot

boreal ravine
#

also its administrator=True

#

idk if its case sensitive

junior verge
#

It says in the docs

slate swan
slate swan
#

Why this happens?

←[33m[=] SamTheNoob#4854 Moved from General to Idle at [2021/Oct/11 - 02:31 PM]←[0m

Instead of writing it in yellow?

This is my code:

cprint(f"[=] {member} Moved from {before.channel.name[2:]} to {after.channel.name[2:]} at {time}", 'yellow')
#

The cmd doesn't support colors

#

Use Windows Terminal or an UX-like terminal, or don't use colors

keen kraken
#

Does anyone know how to hack wifi password using python ?

unkempt canyonBOT
#

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

keen kraken
#

Sure 👍

slate swan
#

wtf

#

ask the owner

#

also, discord-bots channel

#

Like i need to replace before the .com

#

wat

#

await ctx.send(f"https.//learnpython/{value}.com")

#

Ty man rlly appreciate it

#

how do I get bot status?

#

!d discord.ext.commands.Bot.user

unkempt canyonBOT
slate swan
#

returning a member

#

!d discord.Member.status

unkempt canyonBOT
#

property status: discord.enums.Status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") instead.
slate swan
#

bot.user.status

#

got it, does that return the member's status or if they're online / on dnd / idle / offline?

#

just making sure

#

cuz I need the former

#

hmm

#

this returns if it's online

slate swan
#

or dnd

#

Hii meh where can i learn python also what theme u using

slate swan
#

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

slate swan
slate swan
unkempt canyonBOT
#

property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.

Note

Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.

Note

A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
slate swan
#

ig there's a custom_status aswell

#

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

robust remnant
#

how can i make a role above a specific role

#

when i have both roles' objects

slate swan
#

print(str(bot.user.activity))

slate swan
#

!d discord.ClientUser

unkempt canyonBOT
#

class discord.ClientUser```
Represents your Discord user.

x == y Checks if two users are equal.

x != y Checks if two users are not equal.

hash(x) Return the user’s hash.

str(x) Returns the user’s name with discriminator.
boreal ravine
#

@slate swan why u

#

does the bot have an activity though?

slate swan
#

yeah

boreal ravine
#

wait thats a nonetype error hm

slate swan
#

but why would you get your own activity

#

I need it

#

for a sync loop

#

!d discord.ext.commands.Bot.activity

unkempt canyonBOT
#

property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
The activity being used upon logging in.
slate swan
#

I just realized that you needed your own bot's activity

#

which you can get in code without fetching anything

slate swan
#

even though my bot has an activity

#
print(str(bot.activity))
#

where is that

#

wdym

#

where in the code

#

bot.activity returns None

#

bru

#

where did you put this line

#

uh

#

in a loop?

#
@tasks.loop(seconds=10)
async def sync_status():
  await bot.wait_until_ready()
  print(str(bot.activity))
  log = bot.get_channel(botlog_spam)
  msg = await log.send("Syncing status")
  new = await check_db('status')
  type = await check_db('type')
  if str(bot.activity) == str(new):
    pass
#

then idk

tidal hawk
#

How to convert User object into Member object

slate swan
#

u can't

tidal hawk
#

so i can print ctx user roles?

slate swan
#

why not ctx.author

#

what's the difference between a user and a member object

#

member has a guild adjected to it

tidal hawk
#

from member object i can print roles etc

lament mesa
slate swan
#

ah

tidal hawk
#

i mean ctx.author.roles don't work

slate swan
#

wat

tidal hawk
#

what am i missing

#

()?

slate swan
#

how does ctx.author return a user

#

!d discord.ext.commands.Context.author

unkempt canyonBOT
slate swan
#

hm

tidal hawk
#

hm

slate swan
#

show the whole code

tidal hawk
slate swan
#

you can remove message

#

and the brackets from roles

tidal hawk
#

yeah i know, i was testing

#

even without the message, it aint working

slate swan
#

it should return a member

tidal hawk
#

and without the parantheses aswell

#

yeah but it's returning user xD

pliant hill
#

Give me one sec

tidal hawk
tidal hawk
pliant hill
#

ctx.author.roles

#

This is what I have in my code

#

And it works

tidal hawk
#

wtf

#

bs

pliant hill
#

That’s really strang

slate swan
#

ill predict the comamnd was used in dm

#

*command

pliant hill
#

Yea if it’s used in a Dm then it won’t work but if it is in a server I don’t know what wrong then

tidal hawk
#

lmao

slate swan
#

because ctx.author returns a member if used in a guild ,and user if used in a dm channel

tidal hawk
#

Didn't think that far.. thanks anyways

slate swan
#

np , you can have

#

wait up

tidal hawk
#

jep

#

that check decorator

pliant hill
#

It’s something like that

harsh mirage
#

@tawdry perch i did nothing abt code. it was hard to understand. im still on import discord and run bot

tawdry perch
#

ok, so what did you want to make again?

harsh mirage
#

a soam bot. u spam messages u will get muted and bot will send u in dms 'U r muted for 5 mins'

tawdry perch
#

a spam bot?

harsh mirage
#

mute srry

slate swan
#

anti spam

tawdry perch
#

ok good

harsh mirage
tawdry perch
#

well start by making a simple command, with ctx argument and member argument

#

for member agument remember to use discord.Member as a type of it

#

@harsh mirage , wait. Actually make a on_message event with message argument. I forgot you are making a antispam alrd 😅

harsh mirage
#

it looks rlly complicated

#

abd i already have a muted role

#

and*

tawdry perch
#

good, well make the on_message event with message argument

harsh mirage
#

@on_message.event?

tawdry perch
#

ye

harsh mirage
#

ok

tawdry perch
#

no

#

remove .event

harsh mirage
#

k

marble pilot
#

I am making a clear command(purge)
and i am running over some issues. I tried to make a custom error where it detects if the amount given isnt int and then it sends an embed.

    @commands.command()
    @commands.guild_only()
    @commands.has_permissions(manage_messages=True)
    async def clear(self, ctx, amount):
        if type(amount) != int:
            Error_Embed = discord.Embed(title="Error. Amount should be an integer.", description=f"Value type given: <{type(amount)}>", color=0xFF0000, timestamp=ctx.message.created_at)

            await ctx.send(embed=Error_Embed)
        else:
            task_embed = discord.Embed(title=f"{amount} messages have been cleared.", color = discord.Colour.blue())
            task_embed.set_footer(text=f"{datetime.datetime.utcnow()}")
            await ctx.channel.purge(limit=amount+1)

            await ctx.send(embed=task_embed)

When i am testing and i say like -clear 10 it sends the error.

tawdry perch
#

amount: int, should fix it

marble pilot
#

yeah ik but i want to make a custom error

tawdry perch
#

a global error handler or for specific command?

marble pilot
#

for specific cmd

#

like i did

tawdry perch
#
@clear.error()
#code
marble pilot
#
if type(amount) != int:
            Error_Embed = discord.Embed(title="Error. Amount should be an integer.", description=f"Value type given: <{type(amount)}>", color=0xFF0000, timestamp=ctx.message.created_at)

            await ctx.send(embed=Error_Embed)
        else:

#

ok

tawdry perch
#

well that can work as well

marble pilot
#

yeah but

#

it could be an error for mutch things

#

how do i detect if its a type error.

tawdry perch
marble pilot
#

Like it requires the amount to be int not str

#

yeah but it could be a cmd error bc it didnt loaded or something

#

how do i detect the certain error

tawdry perch
#

in your current code, you would do either py try: x except smth: or ```py
if smth:
#code
else:
raise SomeError

slate swan
tawdry perch
#

I'm not sure, so I just added it

slate swan
#

mhm , its not required

marble pilot
#

and it has the error i told u

tawdry perch
#

I don't have time to fix it atm. But I recommend using a error handler

marble pilot
#

kk

#

ty tho

harsh mirage
#

i added the event. what now?

tawdry perch
#

I will be maybe back in 20 mins

harsh mirage
#

k

#

@slate swan can u help me? anti spam bot (mute)

slate swan
#

what issue do u face with it?

harsh mirage
#

idk how to make the whole thing

#

idk where to start

#

its kinda hard

slate swan
#

@harsh mirage

import discord
from discord.ext import commands

client = commands.Bot(command_prefix = '.')

#

import discord
from discord.ext import commands

client = commands.Bot(command_prefix = 'your prefix')

harsh mirage
#

ok ty

slate swan
#

thats a good start@harsh mirage

#

it gives your bot a prefix

harsh mirage
#

ok

#

@slate swan but that means i will run the bot with bot.run or smth like that instead of
client = MyClient()
client.run('TOKEN')

slate swan
#

@harsh mirage

#

import discord
from discord.ext import commands

client = commands.Bot(command_prefix = '.')

@client.event
async def on_ready():
print("Bot is ready")

client.run("")
harsh mirage
#

ty

river kindle
#

I'm doing an anti ghost ping command, the code is only right that when I try it the bot doesn't give an answer.

here the code:


  async def on_message (self, message):
        word_list = ['@everyone', '@here']

        # don't respond to ourselves
        if message.author == self.user:
            return

        messageContent = message.content
        if len (messageContent)> 0:
            for word in word_list:
                if word in messageContent:
                    await message.delete ()
                    await message.channel.send ('Hey don't ghostping.')```
tough wagon
#

how can i send '_io.BytesIO' object in embed.set_image()?

final iron
unkempt canyonBOT
#

Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:

# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")

# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
    file = discord.File(f)

When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.

discord.Embed instances have a set_image method which can be used to set an attachment as an image:

embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png")  # Filename here must be exactly same as attachment filename.

After this, you can send an embed with an attachment to Discord:

await channel.send(file=file, embed=embed)

This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.

tough wagon
lament mesa
#

discord.File(bytesi_object) and send it

tough wagon
slate swan
#

help

lament mesa
tough wagon
#

thank you!

slate swan
#

can someone help me pls why is it displaying this error

tidal hawk
#

How to check if message was sent from Dmchannel or textchannel..?

#

smth like that

tidal hawk
#

Thanks <3

slate swan
#

I GET A SYNTAX ERROR ON THE TOKEN

elder shuttle
#

So I am trying to make a bot give 1 of 4 roles to everyone on the server. I got everything, but I am facing a problem where I am unable to make it an even spread of the roles. One the roles sometimes ends up with a lot higher percentage of people with the role than the others. Does anyone have any ideas?

stiff nexus
#

how do i know if a cog is not loaded?

    @commands.command()
    async def modules(self,ctx):
        embed=discord.Embed()
        for co in self.bot.cogs:
          embed.add_field(name=f"{co}", value=f"{'{}'.format(utily.done) if co else '{}'.format(utily.error)}", inline=True)
        await ctx.send(embed=embed)
slate swan
#

well.. you can't actually check, there's no method nor attribute or property that returns True or False whether the cog is loaded or not

#

but what you can do is try to unload it and load it back in a try/except, if the cog is already unloaded it will raise an error which will basically tell you that the cog is not loaded

#

really bad option but that's the only way you can do it without storing your unloaded cogs somewhere when you unload them

slate swan
slate swan
# slate swan HELP

you censored too much of what's raising the error, also it's a syntax error, you're expected to be able to fix those yourself when attempting to use dpy

#

or when making something a little bit more advanced in general

slate swan
#

ik

#

but you censored even the ending string

slate swan
#

and u can't fix that "simple coding"

#

¯_(ツ)_/¯

#

I started today lol

#

you should start by learning python not with a discord bot

#

but anyways, only censor your token not the ' or "

#

and then send again

#

I stopped making it

#

why 😂

#

js is the way to go

#

python is easier than js but u do u

#

ik but my friend says it has lil to no syntax errors

#

syntax errors are usually really easy to fix

#

even js can have syntax errors

#

ik that's why I'm just gonna either learn LUA

#

or stop

#

then keep with LUA

#

since LUA is really fast and the syntax is somewhat similar to python too making it not all that hard to learn

jade jolt
#

Lua is low level too

slate swan
#

yeah

jade jolt
#

even has a discord wrapper if @slate swan is interested in that

slate phoenix
#

Discord.js doesn’t cover everything too

slate swan
#

how can i get rid of the ['']

crystal wind
#

It's a list isn't it?

#

Just do list[0]

slate swan
#

i have {error.missing_perms}

tough wagon
#

just do ', '.join(list)

tough wagon
#

i haven't got this ['']

crystal wind
#

Anyways, I was wondering if it's possible to call another command by doing a command.
This has nothing to do about aliases, I just want to invoke a command with certains parameters is that possible?

slate swan
#

Yes you can

crystal wind
#

How do we do that exactly?

tough wagon
#

await bot.process_commands(message) or await command_function_name(params)

somber musk
#

Hello, I need help with a discord bot. Though, it's JavaScript, if anyone knows js here please help, if not, can you recommend a server that can help me with my js discord bot?

slate swan
slate swan
somber musk
tough wagon
#

!d str.replace

unkempt canyonBOT
#

str.replace(old, new[, count])```
Return a copy of the string with all occurrences of substring *old* replaced by *new*. If the optional argument *count* is given, only the first *count* occurrences are replaced.
tough wagon
#

like await ctx.send(str(error).replace("['", "").replace("']", ""))

crystal wind
tough wagon
#

like you have py @commands.command(name="haha") async def not_haha(self, ctx): ...
you use py elif something: await self.not_haha(ctx)

tough wagon
#

that's what you need

#

ig

crystal wind
#

I mean like if I'm missing an argument in not_haha it will cause an error of missing argument

#

however, I want for the missing argument to redirect the argument to the ctx.author

elder shuttle
slate swan
tough wagon
hasty iron
#

becuase it’s bad?

tough wagon
#

then how better?

hasty iron
#

str.join like you suggested before

tough wagon
#

and error is str

hasty iron
#

what?

tough wagon
#

with ready ['some wth list']

#

omg he has an error handler

crystal wind
hasty iron
tough wagon
#

uh he is using this... i just idk im stupid bye

slate swan
#

okay

tidal hawk
#

Does anybody have some sort of function, which makes all "->" on the same line?

slate swan
#

fixed

scenic moat
#

how do you edit a past message knowing its message id?

hasty iron
#

TextChannel.fetch_message -> Message.edit

scenic moat
#

ohhhhh ok ty

magic ore
#

better to use get_partial_message for things like this

#

(avoids an api call)

slate swan
#
elif message == "true" or "True" or "yes" or "Yes":
            try:
                db.update_one({
                "guild_id": ctx.guild.id},
                 {"$set": {"guild_embeds": True}})
                return await ctx.reply('turned **embeds** on!')
            except:
                return await ctx.reply('failed to turn **embeds** on!')
        elif message == "false" or "False" or "no" or "No":
            try:
                db.update_one({
                    "guild_id": ctx.guild.id},
                    {"$set": {"guild_embeds": False}
                })
                return await ctx.reply('turned **embeds** off!')
            except:
                return await ctx.reply('failed to turn **embeds** off!')
        else:
            return
#

its automatically setting it to true

forest blade
#

!orgotcha

unkempt canyonBOT
#

When checking if something is equal to one thing or another, you might think that this is possible:

if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
cloud dawn
#

i think its also time to learn about .lower()

slate swan
#

if message.lower

#

that's all ik

forest blade
#

If message is a discord.Message object you would want to do, if message.content.lower() in ('true', 'yes'):

slate swan
#

how do i make a command group in cogs

hasty iron
#

commands.group

slate swan
#

File "main.py", line 41, in config role3 = ctx.guild.get_role(config["3"]) TypeError: 'Command' object is not subscriptable

This doesnt make any sense, config is a dictionary, how come all of a sudden this doesnt work, what command object is this IDE smoking, there is no object its just an integer under this name. Im lost...

This is literally all the config.json file has

{"4": 0, "3": 0, "2": 0, "1": 0}```
#

0 Its giving me aTypeError, shouldn't it be giving me RoleNotFound or smth

wheat moth
#

could you give some more code ?

#

@slate swan

slate swan
slate swan
#

Its a json file remember?

#

What is it defined as though

#

If you want to do that I would just make a local dict inside of your py file and then keeping the code the same since it isn’t that much information needed to store inside of another file

#

uh yeah lemme check

#
config = {"4": 0, "3": 0, "2": 0, "1": 0}```
#

wait if i defined it outside of a function

#

would it still work inside?

#

of the*

slate swan
#

main

#

Just put what I did at the top of the file

#

Lmk if that works

#

oh ok

#

wait what no

#

why would i want that

#

What are you trying to do

#

when the code restarts

#

its gonna default back to that

slate swan
#

Are you gonna store stuff inside of the dict?

#

making a configurable settings

slate swan
#

^

slate swan
#

Make the variable inside of the function

#

oh

hasty iron
#

that’s what the error says?

slate swan
#

okay

#

It should fix it

slate swan
#

Lmk

hasty iron
#

are you even loading the json file

slate swan
#

Oh yeah I should’ve asked that

#

What is config defined as

slate swan
#

ill try inside rq

#

What mode are u opening the json in

#

Read right?

slate swan
#

Ok good LOL

surreal current
#

Yesterday I quick made a bot that automatically converts incompatible file attachments to versions with built in Discord players, thought some people could find it useful!

final iron
hasty iron
#

if it’s discord bots related i think it’s fine

native rain
#

i got an error: no module named 'discord'. how do i fix this?

hasty iron
native rain
hasty iron
#

do you know how to use pip

native rain
hasty iron
#

oh so you’re new to python?

slate swan
slate swan
#

but no youre good

native rain
hasty iron
#

that’s no good, you should learn more python

#

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

slate swan
#

skid

slate swan
hasty iron
#

it’s not a great start

#

unless you knew another language before python and you didn’t really need basic stuff

slate swan
#

how can i get the estimates time it will take to give all members a role

pale zenith
hasty iron
#

gives all members a role and calculate the time it took

pale zenith
#

he wants eta

hasty iron
#

there is no way without actually trying it no?

pale zenith
#

if you, await asyncio.sleep(1) between each role add, then multiply the amount of members by that

#

maybe by moer like 1.1 depends on latency

#

or like 1+bot.latency lol

#

and round it and say itll take that much

hasty iron
#

huh

slate swan
#

Question:
How could I make an input user based so for example

value = '0'

@client.command()
async def change(ctx, value):
print("value")

#how could I change the variable value based on the input for the whole program
final iron
#

Bots get rated limited when adding roles right

slate swan
slate swan
final iron
#

Then the above questions answer would be the amount of members divided by the rate limit

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

slate swan
#

i need help

#

@bot.event async def on_ready(): async with aiofiles.open("ticket_configs.txt", mode="a") as temp: pass

#

the one that starts with "async with aiofiles.open"

#

do functions help decrease the speed? like

async def command(ctx, user):
   def myFunction(id, user)```

instead of
```py
async def command(ctx, user):
   do the thing in the function, but in the command```
#

nah not that

#

im tryna get a ticket system

slate swan
#

yeah

#

the aiofiles is what im having a problem with

#

hold on lemme show

#

i already have asyncio

#

LOADED Music.py Ignoring exception in on_ready Traceback (most recent call last): File "C:\Python\lib\site-packages\discord\client.py", line 333, in _run_event await coro(*args, **kwargs) File "C:\Users\mrshe\Documents\ZeroX The Flow\run.py", line 16, in on_ready async with aiofiles.open("ticket_configs.txt", mode="a") as temp: NameError: name 'aiofiles' is not defined

#

@final iron

final iron
crystal wind
#

I'm panicking so hard right now. My cogs used to work perfectly, but now it seems like none of them is working. I don't know why. This is what I have right now. Basically it takes all python files in my cogs file directory and loads them.

#

but somehow in my cogs repertoire, there's this, and somehow it loads it twice.

final iron
#

I have the exact same thing

crystal wind
#

then i don't know why my cogs don't wanna load anymore. im so upset

#

it checks in cogs then it goes in pycache to check them

glacial barn
#

@client.event
async def on_member_remove(member):
  channel = client.get_channel(896475085534289940)
  print("hi")
  await channel.send(f"**{member.mention} has betrayed the Miners's order.**")```
#

I tried the same code on on_member_join, it works fine but why not on on_member_remove?

glossy reef
#

@opal sonnet

opal sonnet
slate swan
#

how can i make it so only certain users can run a command

slate swan
glacial barn
#

intents = discord.Intents.default()

intents.members = True

#

Yes @slate swan

slate swan
#

does it print hi

brave flint
#

DISCORD_GUILD={your-guild-name}, how this command work? And does it work on multiple guild?

crystal wind
#

I wanna die, all my cogs file don't work anymore.

valid niche
valid niche
brave flint
crystal wind
#

I haven't changed this.

#

It started to not load once I was adding another test.py file that I've dragged in my cogs file.

#

I don't know what to do

valid niche
valid niche
brave flint
#

Okay thanks

crystal wind
#

It was to test a new python file for cogs

valid niche
#

And after deleting

#

What happens?

crystal wind
#

None of the cogs want to load.

valid niche
#

Error?

crystal wind
#

The rest that works on the script works properly.

#

No errors, it just ignores them.

valid niche
#

It always either loads them or errors

#

If you have a bad error handler that suppresses unknown errors fix that first

crystal wind
#

I mean, unless if you force to load a specific class of commands, it just cannot find it.

valid niche
#

Hmm we can always try the good old print debugger

#

Go to the line of load_extension

#

One line before add a print

#

And one line after add a print

crystal wind
valid niche
#

See if they both get printed for every extension

crystal wind
#

I find this strange

#

because i don't think it should

valid niche
#

Wut?

crystal wind
#

It prints it twice.

valid niche
#

And that for EVERY extension?

honest wing
#
@bot.command()
async def price(ctx, price: int):
    if price < 100:
        value = {price}*.40
        hi = discord.Embed(description=f'`>` Price of {price} million is {value}', color=0x8379da, timestamp=ctx.message.created_at)
        await ctx.reply(embed=hi)
    if price > 100:
        value2 = {price}*.35
        he = discord.Embed(description=f'`>` Price of {price} million is {value2}', color=0x8379da, timestamp=ctx.message.created_at)
        await ctx.reply(embed=he)
    else:
        error = discord.Embed(description=f'`>` Please enter valid price', color=0x8379da, timestamp=ctx.message.created_at)
        await ctx.reply(embed=error)```

```py
Command raised an exception: TypeError: unsupported operand type(s) for *: 'set' and 'float'```
i have no clue how to fix this ngl
slate swan
#

what line is the error?

valid niche
#

0.35 is valid

honest wing
#

ohhh

slate swan
#

Sebkuip can u check my dm

honest wing
crystal wind
steel trench
#

Then you have to make them both ints

valid niche
crystal wind
valid niche
honest wing
crystal wind
#

I'll try it when im back on my pc

shell bear
#

hello i made a task loop alr but do i have to like activate it?

#

cuz it doesnt work

honest wing
#
@bot.command()
async def price(ctx, price: int):
    if price < 100:
        value=float(price)*0.40
        hi = discord.Embed(description=f'`>` Price of {price} million coins is ${value}', color=0x8379da, timestamp=ctx.message.created_at)
        await ctx.reply(embed=hi)
    if price > 100:
        value2=float(price)*0.35
        he = discord.Embed(description=f'`>` Price of {price} million coins is ${value2}', color=0x8379da, timestamp=ctx.message.created_at)
        await ctx.reply(embed=he)
    else:
        if type(price) is not int or float:
            error = discord.Embed(description=f'`>` Please enter a valid price', color=0x8379da, timestamp=ctx.message.created_at)
            await ctx.reply(embed=error)```

so it sends the correct price, but then sends error message, idk lmfao
shell bear
unkempt canyonBOT
#

When checking if something is equal to one thing or another, you might think that this is possible:

if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
visual island
#

and use isinstance() for checking types

honest wing
#

ah

crystal wind
#

@valid niche Hey you still there?

#

I managed to fix my problem, although I just don't know why it doesn't wanna work anymore

crystal wind
#

so basically, everything works until client.load_extension. I'm not sure why it doesn't wanna take the variable there which is kinda weird. If you name the extension explicitly, it will work however.

slate swan
# native rain

when you were installing python, you didnt add pip to path

native rain
honest wing
boreal ravine
boreal ravine
crystal wind
#

i could

#

but it doesn't change anything

slate swan
#

i just said that

shell bear
#

basically ping a channel

slate swan
boreal ravine
boreal ravine
slate swan
boreal ravine
#

That wont work

#

he already tried it

honest wing
#

he tried pip3

slate swan
boreal ravine