#discord-bots

1 messages · Page 981 of 1

slate swan
#

ah you passed a command object

#

wym

sweet pilot
#

isn't this easier? authorized = [guild for guild in guilds if guild.permissions.manage_server]

slate swan
sick birch
#

Oh well I was using React for the front end

#

So Python wouldn’t really work

slate swan
#

so str(token) should work?

sweet pilot
#

but yd u said u use tabnine?

sick birch
sweet pilot
slate swan
sweet pilot
#

i do react too so i might able to understand the code

sick birch
#

And it’s not worth increasing bundle size by adding discord.js

slate swan
sick birch
#

I have some un pushed commits on my computer with the new code on it

sweet pilot
lofty pecan
#

Hi there, I made a command to be able to vote for a character every 24h using commands.Cooldown but if the name input isn't correct it sends an error message to the user. Now, the issue is that if you don't put a correct name you're still on cooldown for 24h, how can I fix it so you don't have to wait for that long ?

slate swan
#

Hi

sweet pilot
slate swan
#

👋

slate swan
#

Pfp change again

lofty pecan
slate swan
#

How to get on_ready how long it took to start up?

sweet pilot
slate swan
slate swan
#

And then how do I get the time it took to startup

sweet pilot
#

I have used kite and that one. python extention had it better

slate swan
#

Difference between them is the time difference....

sweet pilot
#

and never thought kite was batter than tabnine cz kite's older

slate swan
#

why would you even record the time your bot takes for it to populate its cache?

lofty pecan
slate swan
#

It would still need a cache/database

slate swan
#

!custom-cooldown maybe utilise this

unkempt canyonBOT
#

Cooldowns in discord.py

Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.

from discord.ext import commands

message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)

@bot.event
async def on_message(message):
    bucket = message_cooldown.get_bucket(message)
    retry_after = bucket.update_rate_limit()
    if retry_after:
        await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
    else:
        await message.channel.send("Not ratelimited!")

from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.

slate swan
#

You can have your own cooldown bucket

#

how have i never seen this before lmfao

olive osprey
# slate swan And then how do I get the time it took to startup

You can just declare a variable with the current datetime at the start:

import datetime
StartTime = datetime.datetime.utcnow()

and then just declare another variable inside your command:

@bot.command()
async def test(ctx):
  x = StartTime - datetime.datetime.utcnow()
  await ctx.reply(x)
lofty pecan
#
async def vote(self, ctx, *name):
        """ Vote system for your favourite OCs"""
        id = ctx.guild.id
        name = " ".join(name)
        cursor = self.db.cursor()
        cursor.execute('SELECT DISTINCT oc_name FROM main WHERE guild_id = ?', (id,))
        result = cursor.fetchall()
        if name in result[0]:
            cursor.close()
            cursor = self.db.cursor()
            cursor.execute('UPDATE main SET oc_rank = oc_rank + 1 WHERE guild_id = ? AND oc_name = ?',(id,name))
            self.db.commit()
            cursor.close()
            await ctx.send('Thank you for your vote!')
        else:
            await ctx.send('Invalid name')
``` that's my code for the moment
slate swan
#

Oh

#

Oka thank

lofty pecan
#

So I could make message_cooldown_vote = commands.CooldownMapping.from_cooldown(1.0, 86400, commands.BucketType.user)

#

then bucket = message_cooldown_vote.get_bucket(message) retry_after = bucket.update_rate_limit()

#

(inside my command)

lofty pecan
frozen patio
#

Hmm

lofty pecan
#

right...?

slate swan
#

Yo I m having some trouble sending an image in an embed. I am using igur. I can send one image but the second i change the URL to the image I want it doesn't send. could the image be too big for the embed and it can not minimize it?

lofty pecan
#

it works now lol

slate swan
slate swan
slate swan
lofty pecan
#

and that wasn't the problem

slate swan
slate swan
#

never wanted to give extra over-smartness

lofty pecan
#

And I just told you that wasn't the issue but it felt like you thought it was a problem

slate swan
lofty pecan
#

lmao

sullen pewter
#
@client.command()
@commands.has_permissions(administrator=True)
async def giveaway(ctx):
    # Giveaway command requires the user to have permissions to function properly

    # Stores the questions that the bot will ask the user to answer in the channel that the command was made
    # Stores the answers for those questions in a different list
    giveaway_questions = ['Which channel will I host the giveaway in?', 'What is the prize?',
                          'How long should the giveaway run for (in seconds)?', ]
    giveaway_answers = []

    # Checking to be sure the author is the one who answered and in which channel
    def check(m):
        return m.author == ctx.author and m.channel == ctx.channel

    # Askes the questions from the giveaway_questions list 1 by 1
    # Times out if the host doesn't answer within 30 seconds
    for question in giveaway_questions:
        await ctx.send(question)
        try:
            message = await client.wait_for('message', timeout=30.0, check=check)
        except asyncio.TimeoutError:
            await ctx.send(
                'You didn\'t answer in time.  Please try again and be sure to send your answer within 30 seconds of the question.')
            return
        else:
            giveaway_answers.append(message.content)

    # Grabbing the channel id from the giveaway_questions list and formatting is properly
    # Displays an exception message if the host fails to mention the channel correctly
    try:
        c_id = int(giveaway_answers[0][2:-1])
    except:
        await ctx.send(f'You failed to mention the channel correctly.  Please do it like this: {ctx.channel.mention}')
        return
#
# Storing the variables needed to run the rest of the commands
    channel = client.get_channel(c_id)
    prize = str(giveaway_answers[1])
    time = int(giveaway_answers[2])

    # Sends a message to let the host know that the giveaway was started properly
    async def message(ctx, user:discord.Member, *, message=None):
        await ctx.send(
        f'The giveaway for {prize} will begin shortly.\nPlease direct your attention to {channel.mention}, this giveaway will end in {    } seconds.')

    # Giveaway embed message
    give = discord.Embed(color=discord.Color.orange())
    give.set_author(name=f'Giveaway!', icon_url='https://i.imgur.com/VaX0pfM.png')
    give.add_field(name=f'Prize: {prize}!',
                   value=f'React with 🎉 to enter!\n Ends in {round(time / 60, 2)} minutes!', inline=False)
    end = datetime.datetime.utcnow() + datetime.timedelta(seconds=time)
    give.set_footer(text=f'Giveaway ends at {end} UTC!')
    my_message = await channel.send(embed=give)

    # Reacts to the message
    await my_message.add_reaction("🎉")
    await asyncio.sleep(time)

    new_message = await channel.fetch_message(my_message.id)

    # Picks a winner
    users = [user for reactions in new_message.reactions
        async for user in reactions.users()
        if user != client.user]
    winner = random.choice(users)
    print(users)
    

    # Announces the winner
    winning_announcement = discord.Embed(color=discord.Color.orange())
    winning_announcement.set_author(name=f'The Giveaway has ended!', icon_url='https://i.imgur.com/DDric14.png')
    winning_announcement.add_field(name=f'🎉 Prize: {prize}',
                                   value=f'🥳 **Winner**: {winner.mention}\n 🎫 **Number of Entrants**: {len(users)}',
                                   inline=False)
    winning_announcement.set_footer(text='Thanks for entering!')
    await channel.send(embed=winning_announcement)```
#

How can I change the time to minutes, hours and days

slate swan
#

!pip time-str

unkempt canyonBOT
slate swan
#

Use this mb

sullen pewter
#

Ok

last moss
#

proxy_url and url?

#

whats the difference

slate swan
last moss
fallow mauve
#

so i got ratelimited(using replit) and then used kill 1 in the shell and it still says im rate limited

slate swan
#

oh well, but still "that" question wasnt related to dpy

slate swan
fallow mauve
slate swan
#

lmao

last moss
slate swan
#

what do you expect the cached version

last moss
#

Don't exactly know what cached means ill be honest

#

dk why you would assume I would?

slate swan
last moss
#

ok thanks

slate swan
last moss
#

thats not what okimii said

slate swan
#

nvm then

last moss
#

I mean Ik what cache is in a cpu

slate swan
#

in some cases it can be temporary but it depends.

last moss
#

but i don't think thats the same

slate swan
slate swan
maiden fable
#

It's stored in RAM cz the read write speeds of a RAM is more than that of a SSD or HDD

slate swan
#

remember ram stands for random accessible memory

slate swan
#

same thing

#

no

last moss
#

it actually is

#

its just shortened

slate swan
#

still used in different contexts

last moss
#

in this case you can say accessible

maiden fable
#

This debate can be taken to an ot channel too

slate swan
#

hunter is the smartest among us all :)

#

i came here for the first time of the day to come to this

#

🗿

#

lmao, idk why i'm even talking about that

slate swan
maiden fable
slate swan
#

!ot anyways

unkempt canyonBOT
slate swan
#

i would love to

slate swan
#

and i said the day not night

#

so you're wrong.

hollow plover
#

discord.errors.InteractionResponded: This interaction has already been responded to before how can i fix this and make it a continupus game?

slate swan
hollow plover
#

alr lemme try that

sick birch
#

Depending on replit's architecture

slate swan
hollow plover
sick birch
#

Probably because it runs on docker or some other container

#

Killing root would probably kill the container and give you a new one

#

But new container could be in the same cluster as old one, same IP

hollow plover
#

?

slate swan
sick birch
#

Since you can just spin one up and shut it down after a user's done

maiden fable
slate swan
#

thought so

maiden fable
#

Please add the Python formatting

brave forge
#

why does the bot not give an answer when pressing the button ???!

brave forge
maiden fable
#

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

silent ridge
#

Hey guys, I made a discord bot, but when I wait around 5 minutes and I train again to click on the verify button it says this

#

but the bot is still online

brave forge
#

@maiden fable так ?

maiden fable
#
@bot.command()
async def text(ctx):
    await ctx.send(
        embed = discord.Embed(title= 'Команды сервера', colour=0xF1C40F),
        components = [
            Button(style = ButtonStyle.green, label= 'Like'),
            Button(style = ButtonStyle.red, label= 'Dislike')
        ]
    )
    response = await bot.wait_for('button_click')
    if response.channel == ctx.channel:
        if response.component.label == 'Like':
            await response.respond(context= "Молодец")
        if response.component.label == 'Dislike':
            await response.respond(context= "Дебил")
frozen patio
silent ridge
frozen patio
#

Like there is a 1-3 minute time then they do not work anymore

silent ridge
#

yes

brave forge
silent ridge
frozen patio
#

Hmm

hardy yoke
silent ridge
#

thanks!

brave forge
#

@maiden fable and why was this format needed ??

maiden fable
#

@brave forge what is the issue

brave forge
#

@maiden fable
Only for some reason, when the button is pressed, the bot does not give an answer
Only for some reason, when the button is pressed, the bot does not give an answer
Only for some reason, when the button is pressed, the bot does not give an answer
Only for some reason, when the button is pressed, the bot does not give an answer

maiden fable
#

Can u print response.component.label?

slate swan
maiden fable
#

Huh?

#

I mean, it isn't my code

brave forge
maiden fable
#

That is the issue

#

can u print response.component?

#

Why do u have a print?

brave forge
maiden fable
#

Wym

brave forge
#

@maiden fable I must say right away I am not an Amerekan and I don't know English well so I don't understand your abbreviations

maiden fable
#

Ah, wym means What you mean

slate swan
#

If anyone that knows or can shed input I'd appreciate it. Basically trying to get my command to work if member has assigned role or administrator permissions. I can only find documentation on, .has_any_role my commands currently work with , @commands.has_permissions(administrator=True) but I'd like to add in, @commands.has_any_role("SupportUS", "SupportCAD") as well as any user with admin permissions, or will I just have to use any role & put admin role in there?

brave forge
#

@maiden fable
I did it on video and the dude on the vidos everything works, I wrote nothing works

maiden fable
#
@bot.command()
async def text(ctx):
    await ctx.send(
        embed = discord.Embed(title= 'Команды сервера', colour=0xF1C40F),
        components = [
            Button(style = ButtonStyle.green, label= 'Like'),
            Button(style = ButtonStyle.red, label= 'Dislike')
        ]
    )
    response = await bot.wait_for('button_click')
    if response.channel == ctx.channel:
        print(response.component)
        if response.component.label == 'Like':
            await response.respond(context= "Молодец")
            print(response.component)
        if response.component.label == 'Dislike':
            await response.respond(context= "Дебил")
            print(response.component)
#

Change your code to this

sick birch
unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
maiden fable
#

@sick birch do u mind helping @brave forge with his issue?

sick birch
#

Yeah i was about to play a game but sure i'll do it after

#

what's the issue?

brave forge
#

@maiden fable when the button is pressed, an error appears in the "Interaction Error" discord

sick birch
#

And code?

sick birch
#

I see

#

I don't remember button_click being a native discord.py event - are you using like discord_components or something?

maiden fable
#

He is using a 3rd party lib since components kwarg

slate swan
brave forge
#

@sick birch yes, that's right, I do it using discord_components

sick birch
#

Please let me know if that helps you, it would mean a lot to me ❤️

sick birch
brave forge
sick birch
#

So can forks like disnake

brave forge
slate swan
# sick birch !d discord.ext.commands.has_role

But how can it work with specific Role & then users with admin perms as well for that one command, instead of one or the other. Can it check first & if no roles specified returned then it checks for admin permissions

brave forge
#

@sick birch can you give me some advice ? is it better to do event and command in the same file or separate them ?? Using Cogs

sick birch
#

Those are really bad and tell you to use code that doesn't work most of the time, and use bad design choices like using discord_components

sick birch
#

Nvm, misread

brave forge
sick birch
#

You want admin perms AND some role?

sick birch
#

Are you watching a youtube tutorial for that?

#

@slate swan you can stack has_permission and has_role

brave forge
#

yes

sick birch
#
@commands.has_role(...)
@commands.has_permission(...)
async def my_command(...):
  ...
slate swan
sick birch
# brave forge yes

That explains it. I suggest you don't follow them since they're pretty terrible

slate swan
#

Let me try something else, one second

sick birch
#

In that case, you could add a check inside the command, like so:

@bot.command()
async def my_command(...):
  if not user_has_admin: return
  if not user_has_role: return

just psuedocode of course

brave forge
slate swan
sick birch
brave forge
sick birch
#

The documentation and examples

empty quest
#

is a VPS a good idea for hosting a discord bot?

frozen patio
sick birch
frozen patio
hollow crag
empty quest
#

which website do you recommend for a VPS?

frozen patio
sick birch
#

I also have a dashboard so i get a domain from R53

frozen patio
#

Nice

#

Robin got a hella nice setup

sick birch
#

Yup

#

Also use S3 :D

slate swan
#

and then, personal opinions

frozen patio
worthy mantle
#

when you type / into the message bar, discord shows all the commands from each discord bot.
how would I make it so my bot's commands also show up?

boreal ravine
#

not normal commands

worthy mantle
#

ik

worthy mantle
sick birch
boreal ravine
#

What library are you using

worthy mantle
sick birch
#

await tree.sync() in on_ready()

unkempt canyonBOT
#
Not gonna happen.

No documentation found for the requested symbol.

boreal ravine
#

ok

frozen patio
boreal ravine
frozen patio
#

Mmmmm

#

Yea

boreal ravine
#

don't do it in on_ready

sick birch
#

Usually, yes, but in this case there's nothing wrong

cold sonnet
#

sounds weird to me

#

it syncs many times

sick birch
#

nothing wrong with keeping it up to date

worthy mantle
#

what tree?

#

discord.tree?
client.tree?

cold sonnet
#

yeah but like you sync and it still will be up-to-date an hour later

cold sonnet
worthy mantle
#

hmmm

#

i was using client

cold sonnet
#

!d discord.ext.commands.Bot.tree

unkempt canyonBOT
#

property tree```
The command tree responsible for handling the application commands in this bot.

New in version 2.0.
cold sonnet
#

does exist

worthy mantle
#

should i not use client = discord.Client()

cold sonnet
#

there's always many ways to do something in programming

torn sail
#

you could do tree = app_commands.CommandTree(client) if using client

cold sonnet
#

you can even make a tree instance and assign it to client

slate swan
#

How can i create
Iwelcome message to send
Invite Tracker
like {member} joined invited by {user} {numInvites}

torn sail
worthy mantle
#

ohk

boreal ravine
magic stump
#

How can i add url

#

to fileds?

worthy mantle
#

yikes 'discord' has no attribute 'app_commands'

paper sluice
boreal ravine
exotic maple
#

I've changed to slash commands recently but im having a issue with the author function...

Error:
AttributeError: 'NoneType' object has no attribute 'author'

exotic maple
# boreal ravine code?

@slash.slash() @commands.has_permissions(ban_members=True) async def ban(ctx, member: discord.User = None, *, reason=None): if member == None: reason = f"Please Mentionthe person you would like to ban {ctx.message.author.mention}" await ctx.send(reason) return await ctx.guild.ban(member, reason=reason) embed = discord.Embed(title=f"{member} Has been banned 🔨 ", description=f"✔ {member} Has been banned from {ctx.guild.name} by {ctx.message.author} for {reason}", color=(0x2fc8ec)) await ctx.send(embed=embed)

boreal ravine
#

hm idk

torn sail
#

Not ctx.message.author

#

Slash commands aren’t invoked from messages

oblique adder
#

what are persistent_modals ? how is it different from normal modals ?

slate swan
#

!d disnake.ext.commands.Greedy

unkempt canyonBOT
#

class disnake.ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.

When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.

For example, in the following code:

```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
    await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
```  An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
slate swan
#

it returns a list right?

maiden fable
#

Persistent modals work even when the bot restarts

boreal ravine
#

theres no such thing as persistent modsls

oblique adder
oblique adder
boreal ravine
#

those are called persistent views

maiden fable
slate swan
oblique adder
exotic maple
#

Looks like it worked, thanks @torn sail

slate swan
#

How can i make welcome message to tag user who called new user on server

final iron
unkempt canyonBOT
#

discord.on_member_join(member)``````py

discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") join or leaves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

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

!d discord.Member.mention

unkempt canyonBOT
slate swan
#

....

velvet haven
#
@commands.Cog.listener()
  async def on_member_join(self, member):
            channel = discord.utils.get(member.guild.text_channels, name='recording')
            if channel:
                embed = discord.Embed(description='Welcome to our guild!', color=random.choice(self.bot.color_list))
                embed.set_thumbnail(url=member.avatar_url)
                embed.set_author(name=member.name, icon_url=member.avatar_url)
                embed.set_footer(text=member.guild, icon_url=member.guild.icon_url)
                embed.timestamp = datetime.datetime.utcnow()

                await channel.send(embed=embed)```
#

is this correct

silver wolf
#

Yeah it looks fine. But I would use embed.timestamp = discord.utils.utcnow() instead

slate swan
#

you should import datetime from datetime and then use utcnow

#

!e py import datetime print(datetime.datetime.now())

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

2022-04-16 18:46:52.515347
slate swan
#

oh nvm it works

boreal ravine
slate swan
#

cool enuf, ill use something similar for welcome message configurations

#

😳 thanks for the idea kayle

slate swan
boreal ravine
#

np step bro

slate swan
#

Hol on how did u do that🙏 is that a new feature

#

!d discord.ui.Modal

unkempt canyonBOT
#

class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.

This object must be inherited to create a modal popup window within discord.

New in version 2.0.

Examples...
slate swan
#

Oh ic

#

Tnx PB_pog

frozen patio
tiny ibex
#
import disnake
from disnake.ext import commands
from audio_bot import start, stop, finished_callback

with open('config.json') as f:
    config = json.load(f)

token = config.get("token")
bot = commands.Bot(command_prefix="!")

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

@bot.commands()
async def record(ctx):
    await start(ctx.author.voice.channel.id, ctx.guild.id)

@bot.commands()
async def stoprecord(ctx):
    await stop(ctx.author.voice.channel.id)

bot.run(token)```
#
import os
import json
import discord
from discord.commands import ApplicationContext, Option

with open('config.json') as f:
    config = json.load(f)

token = config.get("token")

bot = discord.Bot()
bot.connections = {}


async def start(channel_id: int, guild_id: int):
    """
    Record your voice!
    """

    channel = bot.get_channel(channel_id)

    vc = await channel.connect()
    bot.connections.update({guild_id: vc})

    sink = discord.sinks.MP3Sink()

    vc.start_recording(
        sink,
        finished_callback,
        channel,
    )

    return("The recording has started!")


async def finished_callback(sink, channel: discord.TextChannel, *args):
    recorded_users = [f"<@{user_id}>" for user_id, audio in sink.audio_data.items()]
    await sink.vc.disconnect()
    files = [discord.File(audio.file, f"{user_id}.{sink.encoding}") for user_id, audio in sink.audio_data.items()]
    await channel.send(f"Finished! Recorded audio for {', '.join(recorded_users)}.", files=files)


async def stop(channel_id: int, guild_id: int):
    """
    Stop recording.
    """
    if guild_id in bot.connections:
        vc = bot.connections[guild_id]
        vc.stop_recording()
        del bot.connections[guild_id]
        return
    else:
        return("There is no recording going on.")


bot.run(token)```
#

I know there are ton of issues but please tell

junior verge
#

I doubt that this is allowed

#

Recording a vc

tiny ibex
#

it totally works

#

when using pycord alone

honest shoal
#

mee6 does

junior verge
#

Wait fr

slate swan
#

yeah

#

mee6 allows that, nextcord has a voice receive feature too,
Other than that discord.js library has that since djs v7 or smthing

brave forge
#

how to make a server link in embed. That is, on whatever server the command is written, the name of the server is written there. I heard that you need to write like this '{message.guild.name }' but it doesn't work

fallow mauve
#

i wanna make a list of items(like how json files work) that can be edited with commands, but idk any options other than json files

wicked atlas
#

the ; 💀

exotic maple
#

@slash.slash() @commands.has_permissions(kick_members=True) async def kick(ctx, member: discord.User = None, *, reason=None): if member == None: reason = f"Please Mentionthe person you would like to kick {ctx.author.mention}" await ctx.send(reason) return await ctx.guild.kick(member, reason=reason) embed = discord.Embed(title=f"{member} Has been Kicked 🔨 ", description=f"✔ {member} Has been kicked from {ctx.guild.name} by {ctx.author} for {reason}", color=(0x2fc8ec)) await ctx.send(embed=embed)

How do i configure it so that members can't ban their self?

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.

velvet haven
#

whats the code to process commands

exotic maple
#

if ctx.author == member?

#

Yep it worked, thanks

torn sail
#

Ur passing in a list. You could use fetchone instead of fetchall

#

Also you should use this instead of the standard library sqlite3

#

!pypi aiosqlite

unkempt canyonBOT
torn sail
#

Also fetch_channel takes an int not str

#

tuple[0]

steady flume
#

help me pls

#

fix it

torn sail
#

await it

final iron
#

It needs to be awaited

steady flume
#

ok w8

#

same

#
import discord
from discord.ext import commands, tasks
import os
from config import DiscordConfig


class Bot(commands.Bot):
    def __init__(self, command_prefix, **options):
        super().__init__(command_prefix, **options)
        self.on_ready_loop.start()

    @tasks.loop(seconds=900)
    async def on_ready_loop(self):
        print('The BOT continues to work')


prefix = ['test']

client = commands.Bot(command_prefix=prefix, intents=discord.Intents.all(), strip_after_prefix=True,
                      status=discord.Status.dnd, activity=discord.Game('plz help'))
client.remove_command('help')


@client.command()
@commands.is_owner()
async def load(ctx, extension):
    await client.load_extension(f"cogs.{extension}")


@client.command()
@commands.is_owner()
async def unload(ctx, extension):
    await client.unload_extension(f"cogs.{extension}")


@client.command()
@commands.is_owner()
async def reload(ctx, extension):
    await client.unload_extension(f"cogs.{extension}")
    await client.load_extension(f"cogs.{extension}")


for filename in os.listdir("./cogs"):
    if filename.endswith(".py"):
        client.load_extension(f"cogs.{filename[:-3]}")

client.run(DiscordConfig.bot_token)
#

code if so

olive osprey
cloud dawn
#

This is because you can also record people that maybe don't give consent.

steady flume
#

Ok

tiny ibex
slate swan
#

`@client.command()
async def invites(ctx):
embed = discord.Embed(
title="KrkanoidBot - Invites",
colour=discord.Colour.green()
)

total_invites = 0
for i in await ctx.guild.invites():
    if i.inviter == ctx.author:
        total_invites += i.uses

embed.add_field(name="Invites",
                value=f"🔥 Pozvao si {total_invites} {'' if total_invites == 1 else 's'} membera na server!")
print(INFO + f'{ctx.message.author.name} je pozvao {total_invites} korisnika na server.')
embed.set_footer(text="KrkanoidBot - Made by Krkan#9999")
await ctx.send(embed=embed)`

I have one problem when user left server its dont delete one of totalInvites any who can help?

boreal ravine
tiny ibex
#

Don't be mini mod

boreal ravine
#

it's not mini-modding

#

plus, code on a pastebin looks better

tiny ibex
#

And why should I care about your personal preference

#

No reason

#

So I won't

#

Don't bother me for such a useless reason

boreal ravine
#

Chill out mate

#

why are you getting so heated?

cloud dawn
# tiny ibex Don't be mini mod

He is just asking you 2 to make a pastebin since many people here find it annoying to flood the whole chat. If you don't like what the person is saying report it to @novel apex don't confront them.

grave summit
#

hi guys i got my bot running finally with basic await ctx.send commands

#

but now i want to change it so that what ever comes after my command prefix is pasted into the url

#

so i got !ebay working but, i want it to work with !ebay television, so what would i write in order to get "television" stored into a variable

#

so i can format the ctx.send string

wicked atlas
grave summit
#

how would i go about storing "search" so that i can format it into the url my bot sends out

wicked atlas
#

If you enter !ebay television for example, the command is run, and the string "television" is passed in, and stored in search

grave summit
#

i might be making no sense as im v new

#

ahhh

#

so on await ctx.send i could do a formatted string to include {search}

wicked atlas
#

yep

grave summit
#

thank you so much

cloud dawn
#

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

mental tangle
#

Hello - essentially I am trying to code a bot that sends a message when it detects a new game has been installed.
I have everything done, except for the sending a message part

#

For whatever reason when I do:
bot.run(token)

The script completely stops responding and does nothing,.

#

The script stops responding

wicked atlas
#

bot.run isn't something that just runs and continues. It holds up the program in order to run the bot's event loop, and keep the program from exiting to allow it to keep running.

#

I would suggest trying to find a way to merge your code in a way the bot can run it, and now trying to have your code run the bot

grave summit
#

would this work?

#

acc idk why i didnt just test it

wicked atlas
#

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

grave summit
#

await ctx.send(str.replace(' ', '+'(f"https://www.ebay.co.uk/sch/i.html?_from=R40&_nkw=%7Bsearch%7D&_sacat=0&rt=nc&LH_Sold=1&LH_Complete=1%22)))

#

i got syntax error anyway so it deffo not working

wicked atlas
#

Why do you have str.replace?

grave summit
#

i need to swap out spaces with + signs

#

so if they do !ebay playstation 5, when it is formatted its playstation+5

#

otherwise url wont work

wicked atlas
#

First thing, is that for multi-word arguments, you need to add a * argument

@bot.command()
async def ebay(ctx, *, search):
    ...
#

Second, you need to replace the character in the string in search, so you would call replace on that

#

try doing that on it's own before trying to mix it all together

grave summit
wicked atlas
#

What code do you have?

grave summit
#
bot = commands.Bot(command_prefix='!')

@bot.command(name="ebay")
async def ebay(ctx, *, search):
    await ctx.send(f"https://www.ebay.co.uk/sch/i.html?_from=R40&_nkw={search}&_sacat=0&rt=nc&LH_Sold=1&LH_Complete=1")```
#

really appreciate this help

#

thank you

wicked atlas
#

alright, now you just need to replace the spaces in search with +

#

You can do that right in those {} even

grave summit
#

oh really

#

how would i go about doing that

wicked atlas
#

Well, do you know how to use replace?

cloud dawn
#

!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.
frozen patio
#

Hmm

grave summit
wicked atlas
#

you just put it in the {}

grave summit
#

ah

frozen patio
grave summit
#

jo jon, yeah i am

frozen patio
#

Mmmmm

#

Can I see your code?

grave summit
#

how tf i do upticks on mac

#

i been copy and pastin

grave summit
#

oh really ok could you point the out?

#

if you have time

frozen patio
#

You forgot an "

#

I have like 5 hours xD

grave summit
#

oh yeah i think that was just copy and pasting error, i got it in pycharm

slate swan
#

how to create the threads? like message.author.create_theads im lost tbh cuz idk how to create the thread for a specific message

grave summit
#

ebay command is working an everythin i just need to get + instead of space

wicked atlas
frozen patio
#

I think it will do it itself I think

#

It does for my google search command

grave summit
#

nah i get spaces in my url still with the code above

#

{str.replace(' ', '+')search}

#

have i done that in the wrong place

#

that is in the middle of my url

slate swan
frozen patio
#

thread*

slate swan
#

my bad

wicked atlas
#

yeah, actually, looks like you can use spaces @grave summit

torn sail
slate swan
#

!d disnake.Message.create_thread

unkempt canyonBOT
#

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

Creates a public thread from this message.

You must have [`create_public_threads`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.create_public_threads "disnake.Permissions.create_public_threads") in order to create a public thread from a message.

The channel this message belongs in must be a [`TextChannel`](https://docs.disnake.dev/en/latest/api.html#disnake.TextChannel "disnake.TextChannel").

New in version 2.0.
grave summit
slate swan
#

nvm i think it should be message.channel.create_thread

grave summit
wicked atlas
#

check the url in that image

frozen patio
#

Well if you can use spaces why change it

grave summit
#

its not clickable in discord

slate swan
grave summit
wicked atlas
grave summit
#

i get that

frozen patio
#

I use a button

#

They can

grave summit
frozen patio
#

Just do an f string @slate swan

frozen patio
wicked atlas
#

Have you tried mentioning a user in an embed field? I remember that fields don't support all of the formatting that other things l;ike the description do

frozen patio
#

(f"Test test {author.mention}.")

slate swan
wicked atlas
#

Yeah, embed field values aren't able to be formatted like other things on an embed, they only contain plain text

slate swan
#

with/without embed

frozen patio
slate swan
wicked atlas
#

it's one of the two 💀

grave summit
#

await ctx.send(f"https://www.ebay.co.uk/sch/i.html?_from=R40&_nkw={search}&_sacat=0&rt=nc&LH_Sold=1&LH_Complete=1")

#

so where could i put str.replace in that

wicked atlas
#

where search is

slate swan
grave summit
wicked atlas
wicked atlas
frozen patio
#

How I made mine 😃

slate swan
#

whats their question haha

wicked atlas
grave summit
#

{str.replace(' ', '+')search}

dull terrace
#

is there a way to see if someone has clicked a link type button?

wicked atlas
#

replace is a method of a string object, which should be search

search.replace(...)
frozen patio
grave summit
#

thank you, i thought the command was str.replace, but it meant the str which i want to replace haha

dull terrace
frozen patio
wicked atlas
grave summit
#

its working, thank you @frozen patio @wicked atlas wish i could thank you

#

actually so happy with that, im falling in love with coding icl

frozen patio
#

I tried to use an ipc using python but umm it failed

slate swan
#

FortniteDude whats ipc

#

mac?

frozen patio
#

Inter Process Communication

slate swan
frozen patio
#

Connecting a bot to a webserver dashboard

slate swan
frozen patio
#

yeah

#

Mine failed

#

It was that damn permission line

slate swan
#

i should try

frozen patio
#

Ima reopen the folder and fix it

slate swan
frozen patio
#

Mhm

#

Just showed me stuff about the topic searched

frozen patio
slate swan
#

lmao

slate swan
visual yarrow
#

Erm, keep it server appropriate please.

frozen patio
frozen patio
slate swan
frozen patio
#

It is quart-discord I think

slate swan
#

btw how Can i create the threads i mean should i fetch the message or 💀 wut

slate swan
cloud dawn
unkempt canyonBOT
#

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

Creates a public thread from this message.

You must have [`create_public_threads`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.create_public_threads "discord.Permissions.create_public_threads") in order to create a public thread from a message.

The channel this message belongs in must be a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel").

New in version 2.0.
slate swan
#

that doesnt help 💀

cloud dawn
slate swan
cloud dawn
#

You can also create a thread using a partial message, if you got the message id instead of the object.

slate swan
#

whats that 🤔

cloud dawn
#

!d discord.PartialMessage

unkempt canyonBOT
#

class discord.PartialMessage(*, channel, id)```
Represents a partial message to aid with working messages when only a message and channel ID are present.

There are two ways to construct this class. The first one is through the constructor itself, and the second is via the following...
slate swan
#

alr perfect

frozen patio
#

Like this 💀

pliant gulch
frozen patio
#

I have no idea what this is

cloud dawn
#

!d discord.DMChannel.get_partial_message

unkempt canyonBOT
#

get_partial_message(message_id, /)```
Creates a [`PartialMessage`](https://discordpy.readthedocs.io/en/master/api.html#discord.PartialMessage "discord.PartialMessage") from the message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

New in version 1.6.

Changed in version 2.0: `message_id` parameter is now positional-only.
unkempt canyonBOT
#

discord/state.py lines 461 to 462

def _get_message(self, msg_id: Optional[int]) -> Optional[Message]:
    return utils.find(lambda m: m.id == msg_id, reversed(self._messages)) if self._messages else None```
cloud dawn
frozen patio
#

But there is no send_json in my code 💀

pliant gulch
#

send_json is called internally from your IPC library

frozen patio
#

Yeah, so do I need to make a json file

pliant gulch
#

IPC works by opening up a websocket connection and sending information through there, that's how they achieve inter process communication

cloud dawn
pliant gulch
#

Which I'm assuming is just the sentinel value here or something?

#

Make sure you read whatever documentation you followed properly, and make you open a connection

frozen patio
cloud dawn
cloud dawn
frozen patio
cloud dawn
#

!pypi nextcord-ext-ipc

unkempt canyonBOT
frozen patio
#

Yes

#

It is this error that is 👀

#

I have no idea to fix that error

cloud dawn
#

Did it ever work?

frozen patio
#

No

cloud dawn
#

Could you show how you connect?

frozen patio
#

Yeah, the dashboard file?

cloud dawn
#

Have you tried running the examples if it even still works?

frozen patio
#

I have these

chilly knot
#

why is "embeded_response.image.width" returning "Empty"?
the image is showing normal if i send the embed
embeded_response.set_image(url = em_image_url[1])
embeded_image_resolution = f'{embeded_response.image.width}x{embeded_response.image.height}'

frozen patio
unkempt canyonBOT
cloud dawn
#

Type: Optional[int]

frozen patio
#

I think I know the error

#

Wait no

chilly knot
#

"Possible attributes you can access are:" from doks

#

does it mean i can change the pixels?

cloud dawn
chilly knot
#

it works if i try to return the url of the image, width and heigth doesnt

cloud dawn
#

You can't set the height or width of an image.

#

You would need to change the image.

chilly knot
#

dont you think it means that you would get the width and heigth of the image?

#

because i dont input anything, i get a value returned

#

the url for example

slate swan
#

!pypi fortnite

unkempt canyonBOT
frozen patio
#

I got a new error :OOO

#

@cloud dawn Let's goo

frozen patio
#

:0 Dead chat

oblique laurel
#

Anyone here whos used digitalocean, how would i upload my code to a droplet i have running?

slate swan
#

how to get the user who clicked on the button

exotic maple
#

Does anyone know when heroku will allow github connection again?

slate swan
unkempt canyonBOT
green schooner
#

Is there a way to check if a use (that use a command) has a role using the ID of this role?

Like I have the ID of the role stored in a variable and I want it to check if this user has this role

slate swan
unkempt canyonBOT
#

@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.

Similar to [`has_role()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.

This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
slate swan
#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
slate swan
#

check these

green schooner
#

Thank you ❤️

slate swan
# slate swan !d discord.Interaction.user

btw is there a way to get the the author who sent the message that has the thread? like the channel.owner_id returns the user who creates the thread but i want the one that sent the msg

#

idk how to explain PeepoHappy

slate swan
# boreal ravine message.author.id

uhm im using buttons py @disnake.ui.button(label = "Offline", custom_id = "offline", style = disnake.ButtonStyle.grey) async def offline(self, button: disnake.ui.button, inter: disnake.MessageInteraction):

boreal ravine
#

then use a wait_for

pliant gulch
#

!d disnake.MessageInteraction.message

unkempt canyonBOT
pliant gulch
#

Actually, not sure if that would work

slate swan
slate swan
pliant gulch
#

Yea, I was thinking about that

grave summit
#

does anyone know where i can find good instructions for a twitter bot, i want a bot for channel that posts those messages to twitter

#

nothing against TOS

#

just posts the image and text from a message through a tweet

sick birch
#

That’s not within the scope of this channel unfortunately

grave summit
#

ok no problem , thank you anyway

grave summit
boreal ravine
grave summit
#

i couldnt find anything but if im wrong thats fine ill just stop

boreal ravine
#

also, wdym by instructions

grave summit
#

i dont think there is any TOS against twitter bots unless its for smth called "mail bombing" and other bad stuff like viruses

pliant gulch
final iron
#

If you want to make a twitter bot you can use akeno as a wrapper

#

@slate swan

#

🗿

green schooner
grave summit
#

i just want success posts to be shared on twitter when posted in success channels on discord so from what i have read thats fine with TOS but not sure what package is used and cant seem to find one

pliant gulch
#

!d discord.ext.commands.has_guild_permissions

unkempt canyonBOT
#

@discord.ext.commands.has_guild_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.has_permissions "discord.ext.commands.has_permissions"), but operates on guild wide permissions instead of the current channel permissions.

If this check is called in a DM context, it will raise an exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage").

New in version 1.3.
boreal ravine
green schooner
#

Yeah I know about that, I'm trying to have it so it is:

if ctx.message.author.guild_permissions.administrator or #user has a role (using ID):

The ID is stored in a variable

boreal ravine
slate swan
grave summit
green schooner
#

well I will try thx a lot jjkay0Heart

dull terrace
#

quick question to save me 5 mins testing this, can you @ someone in a modal

frozen patio
#

Wdym model?

slate swan
frozen patio
#

Ah

#

I do not know what that is 😅

slate swan
#

me neither

#

they added so many features pog_champ

frozen patio
#

Ikr

green schooner
#

Trying to find a way to check if role is a @role ping, and get the ID of it

async def setmanager(ctx, role):
frozen patio
#

I am gonna learn how to make a leveling system

supple thorn
#

!d discord.Role

unkempt canyonBOT
#

class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild")...
frozen patio
#

👀

supple thorn
green schooner
#

I see

#

thx jjkay0Heart

frozen patio
#

I saw that

#

You still need help or no?

#

With an event

#

an on_raw_reaction_add event

#

I cannot spoonfeed you

#

Mine is very complicated, but it is for a ticket system

#

But you could do this, ig

#

You need to make where the user clicks on the reaction, it will send a DM

slate swan
final iron
#

Nah bro wdym

#

Akeno is the best twitter api wrapper

#

It totally works

slate swan
#

yeah it does lemon_warpaint

#

twitter api is garbo!

frozen patio
#

Why?

slate swan
#

the documentation is horrible

frozen patio
#

Show me

#

Get off replit

#

It's also where you will be ratelimited

#

Did you pass in message?

sick birch
#

It's not

vagrant brook
#

Payload doesnt have message

frozen patio
sick birch
#

agreed

frozen patio
vagrant brook
#

!d discord.RawReactionActionEvent.message_id

unkempt canyonBOT
frozen patio
#

for a code editor at least

vagrant brook
#

Since hes actually using it for hosting

frozen patio
#

Mk

vagrant brook
#

Well you have to work on it yourself, try printing out the variables

supple thorn
#

What did you print?

slate swan
#

bruh

#

discord.Message.id you didn't specify it

#

look, i used to code in dpy and probably don't know much now but i guess it should be payload.message.id

#

try it

final iron
#

discord.Message.id

#

That's not how you do it

slate swan
#

.

supple thorn
#

Where and who

final iron
#

You need an instance of the discord.Message class

supple thorn
#

He also defended replit

slate swan
#

lmao

#

try

supple thorn
#

Capitalization matters

#

No you did Message

#

We can see in the error you did Message

#

Isn't it message_id

slate swan
#

oo

supple thorn
#

I don't work alot with events

slate swan
#

yeah it's message_id prolly

supple thorn
#

But i'm checking the docs

slate swan
supple thorn
#

Coolio

#

You should check the docs more

slate swan
#

docs are pretty easy to use and their helpful!

sick birch
#

"helpful" is debatable

slate swan
pliant gulch
#

Documentation is only helpful when the person who wrote them isn't incompetent

slate swan
#

i think you ment read them?

pliant gulch
#

No, sometimes people just write horrible documentation

#

For an example, when I have to write documentation I just want them done as quickly as possible cause I'm lazy

slate swan
#

in this case its not really bad written. it would be helpful if you actually had the skill to even use the library and read its own documentation

meager quartz
#

ban comand for discord.pyt

#

pls

slate swan
#

!d discord.Member.ban

unkempt canyonBOT
#

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

Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.ban "discord.Guild.ban").
slate swan
#

someone explain to me why it doesnt work now? I did nothing on the code i just restarted my bot. It worked before!

sick birch
#

perhaps

slate swan
pliant gulch
#

!d discord.ext.commands.Bot.process_commands

unkempt canyonBOT
#

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

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").

This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.

Changed in version 2.0: `message` parameter is now positional-only.
brittle flume
#

What's wrong?

class ApplicationModal(ui.Modal):
    def __init__(self):
        x = ui.TextInput(label='Test')
        self.add_item(x)
    
    async def on_submit(self, interaction):
        await interaction.response.send_message('Test success!', ephemeral=True)

Ignoring exception in view <RulesView timeout=180.0 children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Accept' emoji=None row=None>:                                         Traceback (most recent call last):                                       File "/data/data/com.termux/files/home/codes/otaku/venv/lib/python3.10/site-packages/discord/ui/view.py", line 413, in _scheduled_task          await item.callback(interaction)                                     File "/data/data/com.termux/files/home/codes/otaku/extensions/applications/apply.py", line 26, in accept                                        await interaction.response.send_modal(ApplicationModal())            File "/data/data/com.termux/files/home/codes/otaku/extensions/applications/apply.py", line 16, in __init__                                      self.add_item(x)                                                     File "/data/data/com.termux/files/home/codes/otaku/venv/lib/python3.10/site-packages/discord/ui/view.py", line 307, in add_item                 if len(self._children) > 25:                                       AttributeError: 'ApplicationModal' object has no attribute '_children'
tough cedar
#

if i run pip install -e path/to/package to install a local package, and change something in the code, when would the change take effect when that package is used in my bot's code? do i have to restart the bot for it to reflect the changes in that local package?

slate swan
#

yes, ofcourse

#

you need to rerun the bot

tough cedar
#

I see i see, thanks!

tough cedar
slate swan
#

or reloading the cogs if you use them would work too

tough cedar
slate swan
#

given that the libraries should be imported in that cog itself

tough cedar
#

Gotcha

tough cedar
slate swan
#

it should work if its at the top of the file

#

does it raise any error?

tough cedar
#

Oops meant to reply to the 2nd message

slate swan
#

oh understandable

#

what library is it?

tough cedar
#

2.0

slate swan
#

and the other one?

tough cedar
#

Ohh the local one? it's a package I'm developing called gists.py

slate swan
#

oh makes sense

#

well then maybe it needs the bot to restart

tough cedar
#

Thanks!

sullen pewter
barren sand
#

help me

vale wing
#

Maybe you forgot if isinstance(error, MissingRequiredPermissions)?

barren sand
#

can you give me fixed code ?

#
@bot.command()
async def kick_error(error, ctx):
        await bot.send_message(ctx.message.channel, "You do not have permissions")
    elif isinstance(error, BadArgument):
        await bot.send_message(ctx.message.channel, "Could not identify target")

else:
    raise error
#

@vale wing

granite parcel
#
    raise OperationFailure(errmsg, code, response, max_wire_version)
pymongo.errors.OperationFailure: bad auth : Authentication failed., full error: {'ok': 0, 'errmsg': 'bad auth : Authentication failed.', 'code': 8000, 'codeName': 'AtlasError'}
slate swan
granite parcel
#
db = cluster["UserData"]
collection = db["UserData"]

wordstotestby = [
    "word1",
    "word2"
]

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')
    await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name='MongoDB'))

@client.event
async def on_message(ctx): 
    print(f"{ctx.channel}: {ctx.author}: {ctx.author.name}: {ctx.content}")
    myquery = { "_id": ctx.author.id }
    if (collection.count_documents(myquery) == 0):
        if any(x in ctx.content for x in wordstotestby):
            post = {"_id": ctx.author.id, "score": 1}
            collection.insert_one(post)
            print(f"Word detected")
    else:
        if any(x in ctx.content for x in wordstotestby):
            query = {"_id": ctx.author.id}
            user = collection.find(query)
            for result in user:
                score = result["score"]
            score = score + 1
            collection.update_one({"_id":ctx.author.id}, {"$set":{"score":score}})
            print(f"Word detected")```
granite parcel
slate swan
granite parcel
#

but where do i reset it i dont know

slate swan
granite parcel
#

yeah

slate swan
#

lovely

#

idk, create a new user in super users maybe

granite parcel
#

i terminated it

barren sand
#

@slate swan

barren sand
# slate swan if you wanna make seperate error handlers for seperate commands, this is the syn...
@commands.has_permissions(kick_members=True)
@bot.command()
async def kick(ctx, error, user: discord.Member, *, reason="No reason provided"):
        await user.kick(reason=reason)
        kick = discord.Embed(title=f":boot: Successfully Kicked", description=f"User: {user.name}\nReason: {reason}\nCommander: {ctx.author.mention}")
        await ctx.message.delete()
        await ctx.channel.send(embed=kick)
        await user.send(embed=kick)
granite parcel
#

w

#

you have declared perm before declaring the command

slate swan
barren sand
#

I added an error!

slate swan
barren sand
#

early:
async def kick(ctx, user: discord.Member, *, reason="No reason provided"):
now:
async def kick(ctx, error, user: discord.Member, *, reason="No reason provided"):

granite parcel
#

wait what

slate swan
#

thats so wrong

barren sand
granite parcel
#

that maybe working as string?

slate swan
slate swan
vocal snow
granite parcel
barren sand
slate swan
barren sand
#

I need help

#

And not your stupid cynics

#

if you want help me or do not give me an answer

slate swan
barren sand
#

As you know I do not know python programming

granite parcel
#

yeah ur pinged

barren sand
#

Can you write me the correct code?

slate swan
barren sand
slate swan
barren sand
#

thank

slate swan
#

hi Black

granite parcel
#

db = cluster["user"]
collection = db["data"]

placid skiff
#

You cN t use d.py if you don t know py

granite parcel
#

is it wrong?

barren sand
slate swan
#

its an error not a command

#

oh god

barren sand
#

bot.event ?

slate swan
supple thorn
#

To watch

#

Wish you the best ashley

slate swan
supple thorn
barren sand
#

it is not necessary () ?

granite parcel
#

no

slate swan
supple thorn
#

Fuck

slate swan
barren sand
#

Do the English have such a love for guests?

slate swan
#

huh

#

lets keep the chat relevant to the channel, or ping me in any ot channel

granite parcel
#

no errors?

barren sand
#

I was waiting for the bot to write "You do not have permissions"

granite parcel
#

see the logs

barren sand
#

where is my "depressed" ashley ?

#

@slate swan i need you 🥺

#

help me kid

slate swan
#

and no, I wont help you anymore, first learn how to behave properly with others

barren sand
#

Logic 0,0

#

For you I am nothing
And why should my word mean anything to you?

#

If I told you to fly, would you fly?

barren sand
slate swan
#

Hey I am making a bot with giveaways and I was wondering how I could convert 1m to 60s and 1d to the amount of seconds?

barren sand
#

she know python 60%

slate swan
#

Oh ok 😄

#

<@&831776746206265384> help 😔

barren sand
#

Can you send me a friend in 2 minutes? I have to tell you something and then unfriend me

#

@slate swan

granite parcel
#
 db = cluster["user"]
    collection = db["data"]
    author_id = ctx.author.id
    guild_id = ctx.guild.id
    ping_cm = {"command":1}
    ping_cmn = {"_id":author_id}
    collection.find(ping_cmn)
    collection.update({"_id":author_id},{"$set":{"Level":1}})
    await ctx.send("Registered")```
#
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'Collection' object is not callable. If you meant to call the 'update' method on a 'Collection' object it is failing because no such method exists.```
#

@slate swanbro

tall dust
#

!tempban 925079016174682213 1w that is absolutely unacceptable behaviour. read our rules and code of conduct if you return

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied ban to @obtuse obsidian until <t:1650793220:f> (6 days and 23 hours).

tall dust
#

FUCK

#

!unban 925079016174682213

unkempt canyonBOT
#

:ok_hand: pardoned infraction ban for @obtuse obsidian.

tall dust
#

!tempban 942840399767154711 1w that is absolutely unacceptable behaviour. read our rules and code of conduct if you return

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied ban to @barren sand until <t:1650793282:f> (6 days and 23 hours).

placid skiff
#

Self hosting D_D

placid skiff
slate swan
green schooner
#

Hey! I am using a function called CheckManagerPerm() in a cog in this way:

 def CheckManagerPerm(ctx):
        manager_role = ctx.guild.get_role(int(managerID))
        if ctx.message.author.guild_permissions.administrator or manager_role in ctx.author.roles:
            return True
        else:
            return False
 #checkperm
    @commands.command(help="Check if you have the permission to use the bot.")
    @commands.guild_only()
    async def checkperm(self, ctx):
        if CheckManagerPerm(ctx) == True:
          #more stuff

for some reason its sating that:
Command raised an exception: NameError: name 'CheckManagerPerm' is not defined

Is there a specific way to def functions in a cog?

visual island
green schooner
visual island
green schooner
#

I see

#

and do I have to have it as if CheckManagerPerm(self, ctx) == True: in the command?

visual island
green schooner
#

I see

#

Thank you a lot for the help Cirno!

visual island
#

Do you have discord.py on master branch version? You can see this by printing discord.__version__ or by doing pip show discord.py on the terminal.

visual island
vocal plover
#

does it actually not run or is vscode just not resolving correctly?

#

try running it then

slate swan
sacred oyster
#

im importing the discord library and says this message: "

sacred oyster
visual island
#

If you try to run it, does it print anything to the console?

vocal plover
#

ok try py -3.10 -m pip install git+https://github.com/Rapptz/discord.py just to make sure that dpy is being installed on the same python version you're using

#

that's the only reason VSC wouldn't be resolving it if it's installed

visual island
#

You can use the -U flag to check if there's a newer version, so do this: py -3.10 -m pip install -U git+https://github.com/Rapptz/discord.py.

slate swan
#

Hello, I have a bot that has a ticket tool (server enquiries, questions, mod applications, etc), I have created the ticket channel but I have an issue, how am I able to make it so that admins and the ticket creator can see the channel, but the rest of the server not able to see it? I am using py await ticket_channel.set_permissions currently.

green schooner
#

Question, I am in a cog and I am using a variable called managerID this is how its defined:

managerID = open("managerID.txt", "r").read()

I use it in a method like that:

def CheckManagerPerm(self, ctx):
        manager_role = ctx.guild.get_role(int(managerID))
        if ctx.message.author.guild_permissions.administrator or manager_role in ctx.author.roles:
            return True
        else:
            return False

For a reason it keep on saying NameError: name 'managerID' is not defined and I don't get why is there an other way of defining a variable in there?

visual island
trail heart
#

I can't figure out the invalid syntax

slate swan
trail heart
#
    embed = discord.Embed(title="Admin Commands", color=0xC98FFC)
    embed.add_field(name="bubble!purge (AMOUNT)", value="Purge a number of messages in a channel", inline=False)
    embed.add_field(name="bubble!geolocate (IP)", value="Gives general geolocation information about an IP", inline=False)``` 
i cant figure out the invalid syntax
visual island
supple thorn
supple thorn
slate swan
#
  elif (arg.lower() == "admin"):```
slate swan
supple thorn
trail heart
#
    embed = discord.Embed(title="Webhook Commands", color=0xC98FFC)
    embed.add_field(name="bubble!decode (BASE64 CODE)", value="Decode", inline=False)
    embed.add_field(name="bubble!curl (WEBHOOK)", value="Find information about a webhook", inline=False)
    embed.add_field(name="bubble!nuke (WEBHOOK)", value="Delete a webhook", inline=False)
    embed.add_field(name="bubble!troll (WEBHOOK) (MESSAGE)", value="Sends any message of your choice to a webhook", inline=False)
    embed.add_field(name="bubble!spam (WEBHOOK) (MESSAGE)", value="Spams a troll message to a webhook", inline=False)
  await ctx.send(embed=embed)

  elif arg.lower() == "admin": (INVALID ONE)
    embed = discord.Embed(title="Admin Commands", color=0xC98FFC)
    embed.add_field(name="bubble!purge (AMOUNT)", value="Purge a number of messages in a channel", inline=False)
    embed.add_field(name="bubble!geolocate (IP)", value="Gives general geolocation information about an IP", inline=False)```
visual island
green schooner
#

!tag botvar

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!

sacred oyster
slate swan
green schooner
# unkempt canyon

To use this botvar do I have to call it using bot.name? Or just to define it?

trail heart
#

next to where i typed (invalid one)

slate swan
#

Ohh.

supple thorn
supple thorn
trail heart
#

why cant i send screenshots

#

can i msg u dms

supple thorn
#

Show your entire code

visual island
#

A possible reason is that you have a folder/file named discord.py or discord, but you could check by doing print(dir(discord)) for seeing the possible attributes for discord.

slate swan
#
await ticket_channel.set_permissions(author, view_channel = True, send_messages = True, read_messages = True)```
#

Here's the line that gives the issue.

#

Yes, I just realised that just now.

visual island
slate swan
#

Yep, sure worked!

visual island
green schooner
#

And how do you use it cogs?

#

cause it will say that bot is not defined im pretty sure

visual island
#

After you did import discord.

sacred oyster
visual island
sacred oyster
#

and what i do?

#

with what name?

visual island
#

No, it would be

import discord
print(dir(discord)) 
``` and make sure you run it and show what it prints.
#

I guess they did run it before, at least someone told them to.

supple thorn
visual island
# sacred oyster

On the sidebar of replit, find the "lock" image, click it and add the environment variable there.

sacred oyster
visual island
#

You need to pass the intents keyword to the commands.Bot(), so it's something like bot = commands.Bot(command_prefix=..., intents=...). Change the ... to the value you want to pass.

visual island
worthy mantle
#

what is the difference between Discord.Client() and Discord.ext.bommands.Bot()?

sacred oyster
#

shows this error

visual island
#

In your case, it should be something like this:

bot = commands.Bot(command_prefix="n!", intents=discord.Intents.default())
``` or you can pass `discord.Intents.all()` too.
grave summit
#

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