#discord-bots

1 messages · Page 520 of 1

gaunt herald
#

Ok

pliant gulch
#

!customhelp

unkempt canyonBOT
#

Custom help commands in discord.py

To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000

hard trail
#

Can someone send me a full code on an application bot

#

because currently my server needs one

#

So it would be a huge help if someone did

buoyant sage
#

When you guys say post code do you mean the entire 312 line code? Or the command?

#

Sorry I’m new to this

buoyant sage
#

@slate phoenix that

slate phoenix
slate phoenix
final iron
#

My bot is returning py <Message id=895137648736337920 channel=<TextChannel id=813823051774165042 name='📝general' position=5 nsfw=False news=False category_id=789941689791283210> type=<MessageType.default: 0> author=<Member id=868156490022789130 name='Water Boat' discriminator='8161' bot=True nick=None guild=<Guild id=788123028302594079 name="The best gaming server (don't leave)" shard_id=None chunked=True member_count=26>> flags=<MessageFlags value=0>> for some reason

#

Stats of the channel

buoyant sage
#

@slate phoenix

slate phoenix
unkempt canyonBOT
#

Hey @buoyant sage!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

buoyant sage
#

codes 312 lines wont let me send

jade jolt
#

use that link

slate phoenix
#

like the

@bot.command()
async def …..
buoyant sage
jade jolt
#

i dont think his question is d.py related. just a thought

#

its not

final iron
# boreal ravine Code?
    @commands.command()
    async def command(self, ctx, member: discord.Member):
        msg = await ctx.send(f"a")
        await ctx.send(msg)
        await asyncio.sleep(1)
        await msg.edit(content="test")
buoyant sage
#

@slate phoenix hope im not pissing you off lol

boreal ravine
slate phoenix
final iron
#

Oh never realized that

final iron
#

A test command to edit a message

#

That the bot sends

boreal ravine
#

oh

#

why is there a member arg tho

final iron
#

I have it there for something im planning on doing

buoyant sage
#

def send_keepalive(self):
"""
sends PULL_DATA messages from all virtual gateways
:return:
"""
self.last_keepalive_ts = time.time()
for gw in self.vgateways_by_mac.values():
data, addr = gw.get_PULL_DATA()
self.sock.sendto(data, addr)

def __del__(self):
    self.sock.close()
boreal ravine
#
    @commands.command()
    async def command(self, ctx, member: discord.Member):
        msg = await ctx.send(f"a")
        await asyncio.sleep(1)
        await msg.edit(content="test")
``` try this I guess
final iron
#

alr

#

I gtg but ill test it tmr

slate phoenix
buoyant sage
slate phoenix
slate phoenix
#

What I would try to do is delete the file that’s giving the error and clone it again it’s possible you may have accidentally delete a line or something

buoyant sage
#

ok so delete the enitre clone, re clone, then try command?

slate phoenix
#

I would try that yeah

buoyant sage
#

lost again lol

slate swan
#

ah

#

python 3.9+?

jade jolt
#

wouldnt it be from .src import messages ?

slate swan
#

yeah

buoyant sage
jade jolt
#

as i said

#

use what i put

buoyant sage
jade jolt
#

from .src import *

buoyant sage
#

change that line to what you said?

jade jolt
#

change from src import to from .src import

buoyant sage
#

ok will try now

novel rampart
#

what is the error

#

this help code i am converting to cogs

boreal ravine
novel rampart
#

traceback

boreal ravine
#

it isnt

#

wheres the attribute part then?

buoyant sage
#

same error

jade jolt
#

show it lol

buoyant sage
novel rampart
buoyant sage
jade jolt
#

.src

#

not src

#

looks different

#

error isnt the same

buoyant sage
#

ive put .src

novel rampart
maiden fable
novel rampart
#

lemme check

buoyant sage
buoyant sage
maiden fable
#

@buoyant sage what's your folder name

#

the main parent folder

buoyant sage
#

C:\Users\qwerty\Desktop\helium-DIY-middleman

#

helium-DIY-middleman

lilac latch
#

What's the maximum number of characters you can use in an embed?

buoyant sage
#

when changed to what you said

jade jolt
#

lol

buoyant sage
#

then got this when changed back

#

over 12 hrs on this 1 problem lol

#

!customhelp

gaunt herald
#

Who is this bot

slate swan
#

Does anyone know how to improve select menu in dislash.py?

fast musk
#

Can one of you all make a wrapper that uses Pydantic plz instead of just forking and renaming imports? Plz K Thx

buoyant sage
jade jolt
#

try it?

slate swan
#
@client.command()
async def test(ctx):
    msg = await ctx.send(
        "This message has a select menu!",
        components=[
            SelectMenu(
                custom_id="test",
                placeholder="Choose up to 2 options",
                max_values=2,
                options=[
                    SelectOption("Option 1", "value 1"),
                    SelectOption("Option 2", "value1"),
                    SelectOption("Option 3", "value 3")
                ]
            )
        ]
    )
    inter = await msg.wait_for_dropdown()
    labels = [option.label for option in inter.select_menu.selected_options]
    await inter.reply(f"Options: {', '.join(labels)}")

Anyone knows how to change this I mean when clicked it shows an embed

jade jolt
#

explain

slate swan
#

Me?

slate swan
buoyant sage
jade jolt
slate swan
jade jolt
jade jolt
buoyant sage
jade jolt
buoyant sage
jade jolt
#

looks like a folder

buoyant sage
#

i had a hunch there was a folder missing

slate swan
# jade jolt wdym "it shows an embed"

I mean when I run this code it does a select menu and when I clicked on option it shows selected option 1 or the option number. I want to change this to embed that means when I clicked on option 1 it should show an embed that I created and when clicked on option 2 it should show the other embed I create that's what I mean u know how to do like that?

jade jolt
#

i dont spoonfeed

#

but i know how

#

ive done it

slate swan
jade jolt
#

lol

#

wait

slate swan
#

Ok

buoyant sage
jade jolt
#

args.configs

buoyant sage
#

oh ok so thats the name of folder that is missing

#

any idea on how to find it if its not in the github file? i wonder how ppl are running the code with that missing folder!..

slate swan
jade jolt
#

i need to find it

sly hamlet
#
   File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
TypeError: on_slash_command_error() takes 1 positional argument but 2 were given``` ```py
    @cog_ext.cog_slash(name='pfp',
                       guild_ids=[479997589790523405],
                       description="This is just a test command, nothing more.")
    async def pfp(self, ctx: SlashContext, member : discord.Member):
        await ctx.defer()
        await ctx.send(member.avatar_url)```

The only thing I'm giving it is the member to get the avatar from
slate swan
jade jolt
#

i have a lot of files

sonic flax
#

what did i do wrong? when i do /ping it doesnt work

slate swan
#

Oh ok

valid perch
#

Why do you have two bot instances..

#

Only have 1 and use that.

#

@sonic flax

visual yarrow
#

Sorry your message was deleted @sonic flax. Something in the code triggered our invite filter.

oblique adder
oblique adder
final kettle
#

any clue why this isnt working?

@client.event
async def on_reaction_add(reaction, user):
  if reaction.emoji == ':clap:':
    print('hi')
valid perch
#

str( reaction.emoji)

fast warren
#

Hey, super new to discord py. I have a User object. I want to know that user's member name inside a specific guild. How would I go about converting the User object into a Member object?

boreal ravine
#

theres a user object? i didnt know that

fast warren
#

I used fetch_user

final kettle
boreal ravine
#

hm

fast warren
valid perch
#

!d discord.Guild.get_member

unkempt canyonBOT
fast warren
#

this is what's printing out

fast warren
visual island
valid perch
fast warren
#

ahh so there's a fetch_member?

boreal ravine
final kettle
#

!d discord.on_reaction_add

unkempt canyonBOT
#

discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.

Note

To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").

This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.

Note

This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
fast warren
visual island
#

or fetch_member

#

your wish

valid perch
unkempt canyonBOT
#

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

Retrieves a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") from a guild ID, and a member ID.

Note

This method is an API call. If you have [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_member()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.get_member "discord.Guild.get_member") instead.
visual island
#

but fetch_member is an API call

#

do you have Intents.members enabled?

valid perch
fast warren
#

fetch_member works here. What would be the reason that fetch works but get doesn't?

#

oh it's something to do with bot permissions?

visual island
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

slate swan
#
 @commands.Cog.listener()
    async def on_member_ban(self, guild, user):
        start = datetime.now().timestamp()
        reason = "Feature Anti-Nuke | Banning Members"
        async with aiohttp.ClientSession(headers=self.headers) as session:
                    
                async with session.put("https://discord.com/api/v9/guilds/%s/bans/%s" % (guild.id, user), json={"reason": reason}) as r:
                            took = round((datetime.now().timestamp() - start), 3)
                            log = await r.text()
                            if r.status in (200, 201, 204):
                                logging.info("Successfully banned %s" % (user))
                                c = self.bot.get_channel(892973735802449943)
                                await c.send(f"Banned %s, took: {took}" % (user))
                            else:
                                logging.error(f"Could not ban %s" % (user))
visual island
#

you needed Intents.members for get_member as it's getting the member from bot's cache

slate swan
#

okay so this will not work at all, no error no nothing

fast warren
#

ahh ok. Aside from having to change it, is there an advantage to get over fetch? Would get just be faster?

unkempt canyonBOT
#

await ban(user, *, reason=None, delete_message_days=1)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Bans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
slate swan
#

i'm not using that

valid perch
slate swan
#

i'm trying to use whatever's faster

fast warren
final kettle
#

any clue why this isnt working?

@client.event
async def on_reaction_add(reaction, user):
  if reaction.emoji == ':clap:':
    print('hi')
oblique adder
slate swan
#

...

slate swan
#

ohhh wait

#

your right

valid perch
oblique adder
fast warren
final kettle
#

nvm got it

visual island
#

no changes to cache, intents, etc

fast warren
#

so Client also has an intents= parameter?

visual island
fast warren
#

nice!

valid perch
#

Bot inherits Client, and Client has all the api stuff

slate swan
#

File "c:\Users\OneDrive\Desktop\featured(bot)\cogs\events.py", line 13, in on_member_ban
start = datetime.now().timestamp()
AttributeError: module 'datetime' has no attribute 'now'

i got this error

oblique adder
slate swan
#

thx

fast warren
#
intents = Intents.default()
intents.members = True

client = discord.Client(intents=intents)
#

so I have it like this, and get_member is still coming back with None

valid perch
#

Did you enable em on your dev portal

fast warren
#

yeah

visual island
#

try chunking the guild, await guild.chunk()

#

dpy should chuck it at startup, but who knows

fast warren
#

ok nice it's working!

#

thank you again!

visual island
stark hearth
#

in discord.utils.get is it ctx.guild.roles or ctx.server.roles?

warped spear
#

why this error?

slate swan
#

yay it worked

stark hearth
#

i am making a mute command

stark hearth
warped spear
slate swan
slate swan
warped spear
warped spear
slate swan
#

show all code pls

warped spear
slate swan
#

every line 13 ^^

#

uhm sure

warped spear
#

alr

slate swan
stark hearth
#
    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def mute(self, ctx, member: discord.Member, reason = None):
        
        if reason == None: 
                    reason = 'No reason provided.'
        
        role = discord.utils.get(member.gulid.roles, name='Gulag')
        role2 = discord.utils.get(member.gulid.roles, name='Nerd')

        await self.bot.remove_roles(member, role2)
        await self.bot.add_roles(member, role)
        
        embed=discord.Embed(
            title="User Muted!", 
            description=f"{member.mention} was muted by {ctx.author.mention}. Reason: `{reason}`! Do `#unmute <@{member.id}>` to unmute the user.", 
            color=0xff00f6
            )
        
        await ctx.send(embed=embed)

if feel like this command is not working because of the discord.utils.get but i just want some verification

#

also it is an CommandInvokeError

#

!d discord.utils.get

unkempt canyonBOT
#

discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.

If nothing is found that matches the attributes passed, then `None` is returned.

Examples

Basic usage...
visual island
#

!d discord.Member.remove_roles

unkempt canyonBOT
#

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

Removes [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s from this member.

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

!d await inter.reply

stark hearth
#

!d discord.Member.add_roles

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.
lament plinth
#

!d discord menus

#

Rj4k

slate swan
#
if not muted_role:
    create role

#

Hey @slate swan can u help me in onething?

#

I will try

#
@client.command()
async def test(ctx):
    msg = await ctx.send(
        "This message has a select menu!",
        components=[
            SelectMenu(
                custom_id="test",
                placeholder="Choose up to 2 options",
                max_values=2,
                options=[
                    SelectOption("Option 1", "value 1"),
                    SelectOption("Option 2", "value1"),
                    SelectOption("Option 3", "value 3")
                ]
            )
        ]
    )
    inter = await msg.wait_for_dropdown()
    labels = [option.label for option in inter.select_menu.selected_options]
    await inter.reply(f"Options: {', '.join(labels)}")

how to change this?
I mean when I run this code it does a select menu and when I clicked on option it shows selected option 1 or the option number. I want to change this to embed that means when I clicked on option 1 it should show an embed that I created and when clicked on option 2 it should show the other embed I create that's what I mean u know how to do like that?

cloud folio
#

Hi, i am trying to get the list of channels in certain category, but this is not working, idk why

cloud folio
#

and when i type 1 it will show me: <property object at 0x0000015DAF19DE00>

slate phoenix
cloud folio
#

oh

slate phoenix
#

!d discord.CategoryChannel.channels

unkempt canyonBOT
#

property channels: List[GuildChannelType]```
Returns the channels that are under this category.

These are sorted by the official Discord UI, which places voice channels below the text channels.
slate swan
slate swan
cloud folio
slate swan
#

I mean something like on_select_menu?

slate swan
#

And then you can do category.channels

slate phoenix
slate swan
slate swan
#

Nothing else

#

Only this and code

cloud folio
slate swan
#

And category id

slate swan
cloud folio
slate swan
#

Oh then what else u use for this?

slate swan
cloud folio
#

yeah

slate swan
#
category = guild.get_channel(category id) # category id for take the channels

for channel in category.channels:
    print(channel.name)
slate swan
#

?

#

!pypi discord-components

unkempt canyonBOT
cloud folio
slate swan
#

Ok

slate swan
#

Like category

#

But here is one more easy way to do that

#

message.guild

cloud folio
#

it works

#

thank you so much

floral jacinth
#

discord.errors.InvalidArgument: Could not resolve appropriate move position

#

why u.U

marsh depot
#

Hi, how can i make the bot send a message after anyone use 5 commands, for example, a user make 5 bot.commands and the bot un the 5th command send an extra message with an anounce.

Anyone know?

marsh depot
#

How can I do that?

dapper cobalt
#

I need to check the docs for the spelling.

#

Though, they meant the discord.on_command. But for what you need, it would be better to check if the command has passed all checks and actually executed.

boreal ravine
#

your quiting what?

dim cedar
#

how to make a (cmd enable or disable) cmd ?

slate phoenix
#

post the error

boreal ravine
#
  1. ur event
  2. ur indentation
#

you forgot an @

#

why do you have two async def's?

slate phoenix
#

but the indentation is

#

yikes

marsh depot
#

Channel is defined?

boreal ravine
#

!d discord.VoiceChannel

boreal ravine
#

got what

#

I already told u the errors though

dim cedar
#

eh why 2 async def in 1 @bot commands?

boreal ravine
#

didnt u have a channel arg though

dim cedar
#

but you are trying to create 2 cmds

boreal ravine
#

if you want it to be like that you'll have to fetch the channel

#

leaving what

marsh depot
dim cedar
#

remove the 2nd line, write afk instead of move in the 3nd line,fix the indents.

dapper cobalt
dim cedar
#

u cant have and u dont need 2 async def to make a cmd bro

#

i made a on_message event

#

but it is only working in 1 server

leaden anvil
#

is it possible to do two components with the same message EX: Select menu and buttons ?

#

Please Tag to reply

valid perch
ocean leaf
#

how can i send a message in a channel if the user does not nave a specific permission? (sorry for my grammer)

leaden anvil
boreal ravine
slate swan
#

Anyone here?

#

@leaden anvil u using select menus?

leaden anvil
slate swan
leaden anvil
slate swan
#

I need to add select menu when I clicked on one option it should show an embed that I made and when clicked on other option it should show other embed

#

Like that

leaden anvil
slate swan
#

What ?I didn't getu

leaden anvil
slate swan
#

Edit

leaden anvil
#

ok then wait

slate swan
#

Ok

quasi pawn
#

how do I trigger a command when someone boosts a server

leaden anvil
#

@slate swan py while True: event = await self.bot.wait_for("select_option", check=None) label = event.component[0].label if label == "": #enter the label or value of the selct menu options await event.message.editembed=em1) #em1 is the embed you want elif label == "": #enter the label or value of the selct menu options await event.message.edit(embed=em1) #em1 is the embed you want elif label == "":#enter the label or value of the selct menu options await event.message.edit(embed=em1) #em1 is the embed you want elif label == "":#enter the label or value of the selct menu options await event.message.edit(embed=em1) #em1 is the embed you want

slate swan
#

Thnx very very much

leaden anvil
slate swan
#

What should add above while true:?

leaden anvil
leaden anvil
dim cedar
# valid perch Code?
@bot.event
async def on_message(message):
    if message.content == "!mute @Riad#1922":
        user = await message.guild.fetch_member(760010546728402975)
        guild = message.guild
        mutedrole = discord.utils.get(guild.roles, name = "Muted")
        await sleep(5)
        await user.remove_roles(mutedrole)
        await message.channel.send("Did you just escaped a Mute @Riad#1922?")  
    await bot.process_commands(message)     ```
#

why this is working in only 1 server?

slate swan
#

@leaden anvil What should add above while true:?

leaden anvil
slate swan
oak warren
oak warren
#

then maybe the message.content doesnt match

dim cedar
#

and this are the same bro

leaden anvil
# slate swan <@839027889608720406> What should add above while true:?

make sure it be like this ```py
@commands.command(name='select-test')
async def select_test(self, ctx):
await ctx.send("We are testing selects!",
components=
[Select(placeholder="Choose what you want to see!",
options=[
SelectOption(
label="Option 1",
value="option1",
SelectOption(
label="Option 2",
value="option2",
),
])]
)
e1 = Embed(title="embed1", description="a really exciting embed")
e2 = Embed(title="embed2", description="a really exciting embed")
e3 = Embed(title="embed3", description="a really exciting embed")

    while True:
        try: # try except is not required but i would recommend using it
            event = await self.bot.wait_for("select_option", check=None)

            label = event.component[0].label

            if label == "Option 1":
                await event.message.edit(embed=em1))

            elif label == "Option 2":
                await event.message.edit(embed=em1))```
#

@slate swan

dim cedar
#

@oak warren

oak warren
#

the muted role is present in both the servers ?

oak warren
#

ok do this add a thing to print the server name just after if message.content ==

#

and then try

#

if it prints then something else is wrong

dim cedar
#

someone said to me i have to enbale intents

#

what are those?

dapper cobalt
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

boreal ravine
#

python 3.10 is unstable?

slate swan
dim cedar
#

what is this error?

dapper cobalt
# dim cedar

Your bot's top role is lower than the user/the mutedrole role.

sweet merlin
#
import discord, os, time, random, asyncio
from datetime import datetime
from discord.ext import commands
class commands(commands.Cog):
    def __init__(self, client):
        self.bot = client
    os.chdir("C:\\Users\\\ASUS\\Desktop\\john-cena\\cogs")

    @commands.command()
    @commands.is_owner()
    async def bal(ctx):
        await open_account(ctx.author)
        user = ctx.author
        users = await get_bank_data()
        wallet = users[str(user.id)["wallet"]
        await ctx.reply(f"{ctx.author.name} balance is: {wallet}")
    
    @commands.command()
    @commands.is_owner()
    async def sc(ctx, user: discord.User, *, jum):
        users = await get_bank_data()
        user = ctx.author
        await ctx.send(f"credit social earned! {jum}")
        users[str(user.id)]["wallet"] += int(jum)
        with open("mainbank.json", "w') as f:
            json.dump(users, f)
        
        
    async def open_account(user):
        users=await get_bank_data()
        with open("mainbank.json", "r") as f:
            users = json.load(f)
        if str(user.id) in users:
            return False
        else:
            users[str(user.id)] = {}
            users[str(user.id)]["wallet"] = 0
            users[str(user.id)]["bank"] = 0
        with open("mainbank.json", "w")
            json.dump(users, f)
        return Trues
        
        
    async def get_bank_data():
        with open("mainbank.json", 'r') as f:
            users = json.load(f)
        return users

i tried to make a discord economy bot but there is an error, any help?

#

error text:

Traceback (most recent call last):
  File "C:\python39\lib\site-packages\discord\ext\commands\bot.py", line 606, in _load_from_module_spec
    spec.loader.exec_module(lib)
  File "<frozen importlib._bootstrap_external>", line 846, in exec_module
  File "<frozen importlib._bootstrap_external>", line 983, in get_code
  File "<frozen importlib._bootstrap_external>", line 913, in source_to_code
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "C:\Users\ASUS\Desktop\john-cena\cogs\economy.py", line 17
    await ctx.reply(f"{ctx.author.name} balance is: {wallet}")
    ^
SyntaxError: invalid syntax

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\ASUS\Desktop\john-cena\main.py", line 36, in <module>
    bot.load_extension(f'cogs.{filename[:-3]}')
  File "C:\python39\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\python39\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.economy' raised an error: SyntaxError: invalid syntax (economy.py, line 17)

update: its line 16

leaden anvil
slate swan
#

how can i get who was banned using an event and AuditLogAction.ban

#

!d discord.AuditLogAction

unkempt canyonBOT
#

class discord.AuditLogAction```
Represents the type of action being done for a [`AuditLogEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.AuditLogEntry "discord.AuditLogEntry"), which is retrievable via [`Guild.audit_logs()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.audit_logs "discord.Guild.audit_logs").
dapper cobalt
slate swan
#

Me using that

dapper cobalt
#

Well, that has an issue.

steep estuary
#

how to get time in 30s

sweet merlin
steep estuary
#

how to take them differently?

#

30 and s

sweet merlin
#

time.sleep(30)?

#

asyncio.sleep(30)?

placid skiff
#

I think he means that he needs a text to time converter

#

You do it like this:

time = "30s"
Amount = time[:-1]
Unit = time[-1]
#

Amount will be the number, unit is the time unit

placid skiff
untold token
#

So this was a question that I had,
its about a method called os.execl

I made a simple command that can reload a program when it is called, I used to to restart discord bot programs, but some devs said that it should be not be used, but I wonder why because they didn't tell me why

import sys
import os


async def restart_program(self):
    python = sys.executable
    os.execl(python, python, * sys.argv)

@commands.command()
@commands.is_owner()
async def restart(self, ctx: commands.Context):

    await ctx.send("Restarting... Allow up to 20 seconds")
    
    await self.restart_program()   
slate swan
#

@leaden anvil is here any problems?

placid skiff
dapper cobalt
# sweet merlin ye

You aren't getting the data from the dict correctly. You are doing users["1"["wallet"] taking user.id as if it's equal to 1.

steep estuary
#

like we pass >mute @winged charm 30s then here how i can get 30 and s seperatly?

#

@placid skiff

slate swan
#

logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.ban).flatten()
logs = logs[0]
user = logs.user.id
banned = logs.target.id
rbanned = self.bot.get_user(banned)

reef shell
slate swan
#

and i am trying to unban rbanned and it is returning NoneType

reef shell
#

read the error

leaden anvil
dapper cobalt
slate swan
dapper cobalt
#

!d discord.ext.commands.Bot.fetch_user

unkempt canyonBOT
#

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

Retrieves a [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Note

This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_user "discord.ext.commands.Bot.get_user") instead.
slate swan
#

ohh thx you

dapper cobalt
#

I don't see any use of fetching the user, though. You already have it. logs.user returns the User object.

novel rampart
#

any one can help me

#

how to hide discord bot token in heroqu

placid skiff
#

I know that this is not rilevant to discord.py directly but there is a way to check if a string is formatted nickname#id like?

novel rampart
#

i add screat on it but how ill i add t my main file

#

did any one help me

slate swan
#

after i fetch do i use get?

slate swan
lament mesa
slate swan
dapper cobalt
lament mesa
#

and that this

slate swan
dapper cobalt
slate swan
#
logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.ban).flatten()
logs = logs[0]
user = logs.user.id
banned = logs.target.id
rbanned = self.bot.fetch_user(banned)``` so in this
#

what is the user that banned vs the one that got banned

dapper cobalt
#

What is logs.target??

slate swan
#

the user banned

dapper cobalt
#

Then you already have the user object, why are you trying to get it again??

slate swan
#

that's why i'm asking which variable is the person that banned vs the one who got banned

dapper cobalt
#

Target is the banned user.

slate swan
#

so i'm guessing your saying logs[0] is the user who banned

dapper cobalt
#

logs.user is the responsible of the action, logs.target is what/who the action was made on.

slate swan
#

so that should be correct??

lament mesa
dapper cobalt
dapper cobalt
#

No.

slate swan
#

how so, i am not understanding what you are saying

dapper cobalt
#
name = "scoopy"
myname = name

What's the difference between name and myname?

slate swan
#

nothing

dapper cobalt
slate swan
#

ohhhh

steep estuary
#

how i can check if a message content only have mention of my bot ?

slate swan
#

so how am i supposed to get the member to unban

dapper cobalt
#

You don't need rbanned.

lament mesa
unkempt canyonBOT
#

@lament mesa :white_check_mark: Your eval job has completed with return code 0.

3rd
whole shoal
dapper cobalt
steep estuary
whole shoal
#

Let me check

novel rampart
novel rampart
#

i host that bot

dapper cobalt
novel rampart
#

i want to hide my bot token @dapper cobalt

dapper cobalt
reef shell
novel rampart
dapper cobalt
#

Don't host it on heroku.

slate swan
reef shell
novel rampart
#

i also do like this

novel rampart
dapper cobalt
unkempt canyonBOT
#

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

Unbans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
reef shell
novel rampart
reef shell
#

!d os.environ

unkempt canyonBOT
#

os.environ```
A [mapping](https://docs.python.org/3.10/glossary.html#term-mapping) object representing the string environment. For example, `environ['HOME']` is the pathname of your home directory (on some platforms), and is equivalent to `getenv("HOME")` in C.

This mapping is captured the first time the [`os`](https://docs.python.org/3.10/library/os.html#module-os "os: Miscellaneous operating system interfaces.") module is imported, typically during Python startup as part of processing `site.py`. Changes to the environment made after this time are not reflected in `os.environ`, except for changes made by modifying `os.environ` directly.

This mapping may be used to modify the environment as well as query the environment. [`putenv()`](https://docs.python.org/3.10/library/os.html#os.putenv "os.putenv") will be called automatically when the mapping is modified.
slate swan
#

i have await banned.unban(reason)

slate swan
#

that's prolly why

novel rampart
undone lodge
#

mm

reef shell
slate swan
#

Ik, is user just the id??

novel rampart
slate swan
#

!d discord.Guild.ban

unkempt canyonBOT
#

await ban(user, *, reason=None, delete_message_days=1)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Bans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
slate swan
#

yes it is

dapper cobalt
#

unban takes a user object, not just the user's ID.

slate swan
#

so i do await guild.unban(banned, reason="my reason")

slate swan
dapper cobalt
steep estuary
#

ok

novel rampart
boreal ravine
#

How do i fetch a role in a guild?

dapper cobalt
#

!d discord.Guild.get_role

unkempt canyonBOT
boreal ravine
#

oh

#

its get and not fetch?

dapper cobalt
#

Yes. It's stored in the bot's cache.

slate swan
#

how if cache pronounced

#

is*

final kettle
#

could someone help me install the new discord components

slate swan
#

If you don't show the error you're facing, no we can't

wind meteor
dapper cobalt
wind meteor
boreal ravine
#
    @commands.command()
    @commands.guild_only()
    async def github(self, ctx):
      role = ctx.guild.get_role(895210078133710929)
      
      await ctx.author.add_roles(role)
      
      if ctx.author.role:
        await ctx.author.remove_roles(role)

      embed=discord.Embed(
        description='Removed the `github` role!'
      )
      embed.author(name=ctx.author, icon_url=ctx.author.display_avatar)
      embed.timestamp=datetime.utcnow()
      await ctx.send(embed=embed)
``` ```py
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 352, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/db/cogs/errors.py", line 46, in on_command_error
    raise(error)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 995, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 895, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 177, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'role'
``` it isnt letting me add a role to the author for some reason?
#

i don't know if adding/removing roles works for the author though (ctx.author)

vale pine
#

help

#

the

#

ffmpeg on discord.bot

#

doesn't act

#

[youtube] wDgQdr8ZkTw: Downloading webpage
[youtube] Downloading just video wDgQdr8ZkTw because of --no-playlist

#

it is importing song to bot's mic with youtube_dl

dapper cobalt
#

!ytdl

unkempt canyonBOT
#

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)
dapper cobalt
#

!d discord.Member.add_roles

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.
dapper cobalt
#

!d discord.Member.remove_roles

unkempt canyonBOT
#

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

Removes [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s from this member.

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 removed [`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.
boreal ravine
#

hm

dapper cobalt
boreal ravine
#

I just did if role in ctx.author.roles instead of ctx.author.role because apparently author has no attribute role

floral jacinth
#

how can set in channel rules, a single member can change its name?

dapper cobalt
vale narwhal
#
@bot.event
async def on_member_update(member):
   role = bot.get_role(864830377741647872)
   if user.id == 650516102488784934:
      await member.add_roles(role)

Uhh am i doing anything wrong why the bot didn't add the role

dapper cobalt
#

What is on_role_remove? I'm pretty sure that's not an event.

leaden anvil
#

Can some body help me: Ok I want to edit a message after a select menu event is done but it gives me the error Command raised an exception: TypeError: feedback() missing 1 required keyword-only argument: 'self' why is this I specified self already here is the code: https://paste.pythondiscord.com/vowunuyiwu.csharp

dapper cobalt
bright palm
bright palm
#

You also need the role object to add roles

vale narwhal
#

line 3

bright palm
#

That is just the id

leaden anvil
bright palm
#

Also the .add_roles method is only on the member

#

Not the guild

boreal ravine
#
    @commands.command()
    @commands.guild_only()
    async def role(self, ctx, roles):

      github_role = ctx.guild.get_role(895210078133710929)
      status_role =  ctx.guild.get_role(895210111625224222)
      
      if roles == "github":

        if github_role in ctx.author.roles:

          return await ctx.author.remove_roles(github_role)

          embed=discord.Embed(
            description='Removed the **github** role!'
            )

          embed.set_author(name=ctx.author, icon_url=ctx.author.display_avatar)
          embed.timestamp=datetime.utcnow()
          await ctx.send(embed=embed)
        
        await ctx.author.add_roles(github_role)

        embed=discord.Embed(
          description='Gave you the `github` role!'
          )

        embed.set_author(name=ctx.author, icon_url=ctx.author.display_avatar)
        embed.timestamp=datetime.utcnow()
        await ctx.send(embed=embed)
``` this is my code to remove/add a role but it works fine but when the bot removes a role it doesnt send the message. Can anyone tell me why?
reef shell
#

this is why

boreal ravine
#

hm

reef shell
#

return means it returns from the function

boreal ravine
#

oh it sends that message

#

and ignores everything below?

reef shell
#

it removes the role and exits out from the function

boreal ravine
#

so i should put return at the bottom of the if statement?

boreal ravine
#

thanks it worked sherlock

reef shell
dim cedar
#
async def on_message(message):
    if message.content == "#mute @Riad#1922":
        user = await message.guild.fetch_member(760010546728402975)
        guild = message.guild
        mutedrole = discord.utils.get(guild.roles, name = "Muted")
        await sleep(5)
        await user.remove_roles(mutedrole)
        await message.channel.send("Did you just escaped a Mute @Riad#1922?")  
    await bot.process_commands(message)```
this code is not preventing probot's mute . why?
reef shell
#
if message.content == "#mute <@your_id>" or message.content == "#mute <!@your_id>":```
dim cedar
#

it is just displaying my name on discord

#

in my code it is the id

reef shell
#

and is that sleep(5) is asyncio.sleep()?

dim cedar
#

the sleep is fine

#

i figured the problem

#

mee6 and probot creates 2 different muted role

#

but when my code tries to remove it ,it thinks that it has to remove the role that mee6 has created

#

so thats how it doesnt work

#

can any one tell me how can i fix this problem?

leaden anvil
#

Ok so I am getting a exception when I run the script 'NoneType' object has no attribute 'split' why is the since if I do a select menu without the event it works perfectly fine ?

placid skiff
leaden anvil
#

script py @client.group(invoke_without_command=True,) async def feedback( self, ctx, *, text=None, ): try: text = text.split("|") report = discord.Embed(color=0xFFF868) report.add_field( name="Pending Confirmation", value=f"{text[1]} #Tittle \r {text[2]} #Description", ) await ctx.channel.send(embed=report, components=[ Select( placeholder="Where to post", options=[ SelectOption(label="Bugs", value="B"), SelectOption(label="Commands", value="C"), SelectOption(label="Suggestions", value="S"), SelectOption(label="Other", value="O"), ])] ) while True: event = await self.client.wait_for("select_option", check=None) label = event.component[0].label if label == "B": await event.message.edit(components=[[Button(style=ButtonStyle.red, label="Discard", custom_id="n"),Button(style=ButtonStyle.green, label="Send", custom_id="y"),]]) elif label == "C": await event.message.edit(components=[[Button(style=ButtonStyle.red, label="Discard", custom_id="n"),Button(style=ButtonStyle.green, label="Send", custom_id="y"),]]) elif label == "S": await event.message.edit(components=[[Button(style=ButtonStyle.red, label="Discard", custom_id="n"),Button(style=ButtonStyle.green, label="Send", custom_id="y"),]]) elif label == "O": await event.message.edit(components=[[Button(style=ButtonStyle.red, label="Discard", custom_id="n"),Button(style=ButtonStyle.green, label="Send", custom_id="y"),]]) except: await ctx.reply("Please enter `/feedback format` to check how to format.")

placid skiff
#

Essentially the variable u are trying to split is not a string object

leaden anvil
leaden anvil
placid skiff
#

The text is None as default
So if you don t pass any values to text it is a NoneType object

placid skiff
#

Mhhh

#

I check the docs, gimme a sec

leaden anvil
#

ok

placid skiff
#

Well, that sure is weird
Just to try, before the try - except write this:

text = ctx.content.strip("/feedback ")
leaden anvil
placid skiff
#

What the hell?
Your ctx is passed as a string? Bruh?

leaden anvil
placid skiff
#

It is a cog am i right?

#

Can you write the whole code on paste bin or something and send the link to me?

leaden anvil
#

also formatting

placid skiff
#

Well no problem, copy the whole file somewhere and send it to me xD

placid skiff
#

Ok i guessed it right

#

You re using self but you re not inside a class

#

So your self parameter actually is the context of the command

#

And ctx is the argument you pass after you write the command

placid skiff
#

Also, why you have a comma after your (invoke_without_command=True)?

slate swan
#

is there anyway to use express-py and make my bot send a DM when it gets an upvote? or use webhooks

#

Why not using the library of the bot list?

slate swan
slate swan
unkempt canyonBOT
slate swan
#

hmm

slate swan
#

I'll see what I can do after reading docs

#

This library is actually so bad xD

#

No documentation and doesn't support webhook events

#

true , no docs

#

well , if they ask in their server it will be helful

#

I don't even think this bot website has good api wrappers at all

#

thats the only wrapper they designed

#

oh wait

#

there are no docs

#

yeah

#

that sucks

#

Hey where can I learn python?
And how can I make discord bots by python??

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
#

wait than how do I learn about dblapi than?

#

Ok thx :)

slate swan
slate swan
#

It's pretty bad

#

And doesn't do what you want anyways

slate swan
slate swan
#

than how do I send a DM when my bot gets an upvote

slate swan
#

Create an API

#

And use what's written in the vote-webhooks

#

Should ask in their server though

#

by api they actually meant creating a scenerio a.k.a a webserver their docs actually show how to get data of the voters

#

And that's why I recommend people to use top.gg and not this website xD

slate swan
#

which isnt working

slate swan
#

yikes

#

you know about express-py?

#

Well you need an API either way

#

one of the site helpers told me to use express-py and than make a web server to make the bot send DM use replit for hosting purpose and install a listener

#

What kind of helper is that xD

slate swan
#

I'm pretty sure Flask can do the job actually

slate swan
#

No?

#

and than get data of voters and than make the bot DM?

#

It's not just for a dashboard

slate swan
heavy folio
#

how do i change channel permissions for everyone from default to locked

reef shell
slate swan
#

hmmm

slate swan
reef shell
#

!d discord.TextChannel.set_permissions

unkempt canyonBOT
#

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sets the channel specific permission overwrites for a target in the channel.

The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that belongs to guild.

The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.

If the `overwrite` parameter is `None`, then the permission overwrites are deleted.

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...
heavy folio
#

oh ty

slate swan
heavy folio
pliant gulch
#

None of those

#

That would be strings

heavy folio
#

huh

pliant gulch
#

You want Guild.default_role which is the @everyone role

heavy folio
#

oh so i leave it blank or?

pliant gulch
#

You can't just pass the name you need to pass the object

heavy folio
#

okay ty

heavy folio
# pliant gulch <:this:470903994118832130>

wait, so in the docs it said if i did overwrite = None then it will delete the overwrite, does it delete the overwrite only for that specific perms in that role or all overwrites for the role? what if i wanna keep it as it was previously

pliant gulch
#

It deletes the overwrites in that channel for a target

heavy folio
#

ohh okay ty

slate swan
#

File "<stdin>", line 1, in <module>
NameError: name 'bot' is not defined

||token||

slate swan
# slate swan show code, define bot

import discord
from discord.ext import commands

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

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

bot.run("Token)

#

hm

slate swan
slate swan
#

bot.run("Token) should be bot.run("Token") tho

slate swan
#

strange, the code is correct

#

what should i do?

valid niche
#

!traceback

unkempt canyonBOT
#

Please provide a full traceback to your exception in order for us to identify your issue.

A full traceback could look like:

Traceback (most recent call last):
    File "tiny", line 3, in
        do_something()
    File "tiny", line 2, in do_something
        a = 6 / 0
ZeroDivisionError: integer division or modulo by zero

The best way to read your traceback is bottom to top.

• Identify the exception raised (e.g. ZeroDivisionError)
• Make note of the line number, and navigate there in your program.
• Try to understand why the error occurred.

To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.

slate swan
# valid niche can you get a FULL traceback please?

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

PS E:\Projects\Bot Development\Not decided> & C:/Users/user/AppData/Local/Programs/Python/Python39/python.exe
Python 3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

bot.run("69696")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'bot' is not defined

valid niche
#

I hope that isn't your actual token

slate swan
#

Plese help now

valid niche
#

so i see it's opening the REPR

#

which can be seen from the >>>

#

meaning it's not actually running your file, but instead it's just doing the python REPR

#

and i guess it's inserting your code but not correctly

#

you want the command to be python file.py with file being your actual filename

#

it's now just doing python without the file

warped spear
#

@bitter anchor

slate swan
valid niche
#

you're only running the python.exe

#

what you should be doing is python file.py

#

or python.exe file.py

#

with file.py being your actual bot file

slate swan
#

How do i do that

#

open ur terminal

valid niche
#

by....running python file.py instead of python?

slate swan
slate swan
slate swan
# slate swan go to the directory where ur bot.py or main.py or whateverucallit.py file is

E:\Projects\Bot : The term 'E:\Projects\Bot' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At line:1 char:1

  • E:\Projects\Bot Development\Not decided
  •   + CategoryInfo          : ObjectNotFound: (E:\Projects\Bot:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException
valid niche
#

it's cd path/to/file

slate swan
#

cd 'E:\Projects\Bot'

slate swan
slate swan
#

mate

#

u r already in the directory

#

# https://discord.com/api/v8/channels/885472410176991242/Messages 

r = requests.post() ``` I’m stuck im trying to make discord bot to make @lament oar1 announcement
#

just run python main.py there, replacing main.py with ur file name

valid niche
# slate swan

because there is no E:\Projects\Bot Development\Not Decided\E:\Projects\Bot

#

cd works relative from the file you are in already

pliant gulch
valid niche
#

but i sense a great lack of basic python knowledge if you don't even know how to properly run your python script

pliant gulch
#

the dictionary should have a key, content which has the value of @everyone

#

The headers should look like ```py
{"Authorization": "Bot {token}"}

valid niche
slate swan
#

Hey what's wring in this code?
Why it shows me error (I am learning py 😅)

valid niche
slate swan
slate swan
#

its os.getenv

slate swan
#

Ohk thx :)

#

!d os.getenv

unkempt canyonBOT
#

os.getenv(key, default=None)```
Return the value of the environment variable *key* if it exists, or *default* if it doesn’t. *key*, *default* and the result are str.

On Unix, keys and values are decoded with [`sys.getfilesystemencoding()`](https://docs.python.org/3.10/library/sys.html#sys.getfilesystemencoding "sys.getfilesystemencoding") and `'surrogateescape'` error handler. Use [`os.getenvb()`](https://docs.python.org/3.10/library/os.html#os.getenvb "os.getenvb") if you would like to use a different encoding.

[Availability](https://docs.python.org/3.10/library/intro.html#availability): most flavors of Unix, Windows.
slate swan
valid niche
#

i use vsc and the command it runs is VERY different

slate swan
slate swan
#

@slate swan hey now it shows os is not defined, what should I do?

valid niche
valid niche
# slate swan hmmmmmmmmmmmmm i never use vs code for python anyway

this is the command it normally runs

PS C:\Users\Sebastian Kuipers\Desktop\Tekxitbot>  & 'C:\Program Files\Python310\python.exe' 'c:\Users\Sebastian Kuipers\.vscode\extensions\ms-python.python-2021.9.1246542782\pythonFiles\lib\python\debugpy\launcher' '49994' '--' 'c:\Users\Sebastian Kuipers\Desktop\Tekxitbot\pybot.py'
slate swan
#

Ohk

valid niche
# slate swan why not just `python pybot.py`

that's what a normal human does, but the run button runs it using absolute paths to ensure it actually works when the terminal isn't in the correct directory, and also runs a debugger so it can hook into the stack and help with debugging

slate swan
#

nice

valid niche
#

so you can see that the user here didn't use the actual run button

slate swan
#

hmmmmmm

slate swan
valid niche
valid niche
#

so it's first doing python which opens the REPR, then inserts only the last line of code

heavy folio
#

hi, i did ```py
import discord
from discord import permissions
from discord.ext import commands
from discord.ext.commands.errors import BotMissingPermissions

class Giveaways(commands.cog):
def init(self, bot):
self.client = bot

def setup(bot):
bot.add_cog(Giveaways(bot))

slate swan
#

@slate swan show screenshot of how u r running ur file

slate swan
valid niche
#

doing just python opens a REPR which doesn't work for you

#

you need to do python file.py

slate swan
slate swan
valid niche
#

like you literally already have bot

slate swan
valid niche
#

why use self.client which is against all naming conventions?

slate swan
heavy folio
slate swan
heavy folio
slate swan
#

yes sir

heavy folio
#

right

#

keep forgetting that :/

slate swan
slate swan
#

u sure u have python installed

valid niche
#

it's FAR from a beginner project

slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
# slate swan

show output, like press enter or something, it would either give and error message or run python

valid niche
#

oh also i see a youtube page with a discord bot tutorial

#

i've yet to see a singular youtube video that is actually a good guide

#

main issue is, videos are passive learning, aka one of the worst kinds

slate swan
slate swan
slate swan
#

i mean , you are trying to run the same file right?

valid niche
#

if it's not installed/not on path it opens the microsoft store

#

which is kinda the bad way to install python

slate swan
#

probably python is not added to pat

#

path

valid niche
#

best way to figure out is to dig into program files and find the python.exe

slate swan
#

just open the environment variable settings and check the path variable^

leaden anvil
placid skiff
leaden anvil
#

ok

edgy lion
slate swan
#
client = discord.client()
keywords = {"is new server"}


@client.event
async def on_message(message):
  for j in range(10):
   await message.channel.send("new server")
    
client.run(“token”)```
#

Anyone can see problem in 2nd line

final iron
#

I wouldn't suggest using client though

#

Use discord.Bot()

slate swan
#

Ty

stark bobcat
#

how do i dm a user by username

boreal ravine
unkempt canyonBOT
#

class discord.ext.commands.MemberConverter(*args, **kwargs)```
Converts to a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member").

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order)...
stark bobcat
#

but

boreal ravine
#

wot

stark bobcat
#

how do i do it

edgy lion
boreal ravine
boreal ravine
stark bobcat
stark bobcat
boreal ravine
#

dunno if ur planning to make a command tho

jade jolt
# edgy lion same error

run this
sudo mv /var/lib/dpkg/info/install-info.postinst /var/lib/dpkg/info/install-info.postinst.bad

edgy lion
#

donne

#

done

jade jolt
stark bobcat
#

i am making a ban command and when a user gets ban using the command it should dm the user who got banned

#

dm u got banned

boreal ravine
stark bobcat
#

wail lemma send my code

boreal ravine
#

y

stark bobcat
#
@commands.command()
    async def ban(self,ctx, member: discord.Member, *, reason=None):
        embed = discord.Embed(
            description=f"You have been banned in reason:{reason}", color=0xFF0000)
        await ctx.member.send(embed=embed)
        await member.ban(reason=reason)

        embed = discord.Embed(
            description=f"Successfully banned {member}", color=0x3FFF00)
        await ctx.send(embed=embed)```
boreal ravine
#

u dont need context

stark bobcat
#

oh

#

so member.send only?

boreal ravine
#

yea

stark bobcat
#

ok

#

uh

edgy lion
#

thx

stark bobcat
#
            description=f"Successfully banned {member}", color=0x3FFF00)
        await ctx.send(embed=embed)```
#

this needs ctx tho

stark bobcat
#

uh

boreal ravine
#

you already defined member so why ctx?

stark bobcat
#

no

boreal ravine
#

no?

stark bobcat
#

no to the user

boreal ravine
#

then send it to the member??

#

i dont understand what u want i already told u how to do it

stark bobcat
#

oh

#

ok one min

#

works thanks

slate swan
#

how can i get all of the default emojis?

for emoji in discord.emojis:
  print(emoji)

?

#

ping me when responding please

waxen granite
#

how do i get today's date in my timezone?

#

datetime.datetime.now?

slate swan
#

datetime.datetime.utcnow

#

im pretty sure

waxen granite
#

that is utc date

#

my timezone is 5 and a half hrs ahead of it

slate swan
#

i think this will show the time in ur timezone

#

Use pytz

slate swan
#

erm

#

That's not how you would get a list of all default emojis

boreal ravine
#

!d discord.Guild.emojis

unkempt canyonBOT
boreal ravine
boreal ravine
slate swan
boreal ravine
#

well u can count them

#

i think theres about 300-500 default emoji's

slate swan
#

wdym by counting?

boreal ravine
#

y do u wanna get the amount of emoji's tho

slate swan
#

how is it helping me?

slate swan
boreal ravine
slate swan
slate swan
supple storm
#

are there any good discord.py developer here?? i want to ask how can i make a personal prefix system?? i tried to search for it but the result is server prefix, not personal one

hasty iron
#

it’s the same idea as server prefix

#

instead of saving per-guild its per-user

dapper cobalt
supple storm
#

lol

supple storm
hasty iron
dapper cobalt
slate swan
hasty iron
#

and also caching exists

#

postgresql can handle 10s of thousand of queries persecond

slate swan
slate swan
#

Note that there will be 590 emojis

#

So it's pretty much useless to make it

sonic flax
#

Can someone explain what to do to fix /ping, it doesnt work (besides remove client.command i already did)

slate swan
#

pass_context NotLikeThis

#

Nice emote aka BD

#

delete your client definition

#

and just use bot

slate swan
maiden fable
#

Suppose I am in Guild A, but I want to invoke a command in such a way that the ctx would act as if the command was invoked in Guild B. How to achieve so?

slate swan
#

PROFESSIONAL PYTHON

maiden fable
slate swan
sonic flax
slate swan
sonic flax
#

Also when I do /ping it always shows the same number

#

When it worked before

slate swan
#
@bot.command()
async def hello(ctx):
    guild2 = bot.get_guild(id)
    ctx.guild = guild2
#

prodigy

maiden fable
slate swan
#

!eval @bot.command()
async def hello(ctx):
guild2 = bot.get_guild(id)
ctx.guild = guild2

hasty iron
dapper cobalt
slate swan
#

!eval
async def hello(ctx):
guild2 = bot.get_guild(id)
ctx.guild = guild2

slate swan
#

so bru

dapper cobalt
#

If you change the context's guild you still did not change the context's channel.

#

And the channel is where a message would be sent.

slate swan
#

doesn't have to be send

#

but you can get the guild from the channel, so that's good too

maiden fable
sonic flax
slate swan
dapper cobalt
maiden fable
#

Bro... I don't know which channel is it and I want the channel name only

#

And I can get the channel only when I can get that context from another guild

slate swan
#

And you shouldn't use / as prefix

#

As it interferes with slash commands

maiden fable
#

No....?

slate swan
#

Yes

maiden fable
#

I mean, why would it

dapper cobalt
slate swan
#

If you have a command with the same name as a slash command in the server it will priviledge the slash command

maiden fable
dapper cobalt
maiden fable
#

at last u understand

dapper cobalt
#

Hunter, go practice print statements. You need it. kekw

maiden fable
#

Yea, time to do print "Hi"

dapper cobalt
#

That's python2, hunter.

slate swan
dapper cobalt
#

!e

print "Hello, world!"
unkempt canyonBOT
#

@dapper cobalt :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     print "Hello, world!"
003 |           ^
004 | SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello, world!")?
slate swan
#

OMG

dapper cobalt
#

Only python2.

slate swan
#

ducky_devil that's gonna be me

waxen granite
#
            localdate = datetime.date.today()
            objend = datetime.date(2021, 11, 13)```
how can i get number of days between these 2?
slate swan
#

how do you send more embeds

#

not 2.0

maiden fable
dapper cobalt
maiden fable
#

Who says that...

#

B. R. U. H.

slate swan
#

so the answer is
no?

dapper cobalt
maiden fable
slate swan
maiden fable