#discord-bots

1 messages Β· Page 736 of 1

keen talon
#

No need to do that now , he is learning

slate swan
#

thats why im better

#

im the anime version of you they all love me

keen talon
#

Lol

slate swan
keen talon
#

I didn't read it properly man πŸ˜‚πŸ˜‚

slate swan
#

yeah yeah excusespithink

keen talon
slate swan
keen talon
#

Seriously man

#

Y would I make a excuse lol

#

πŸ˜† πŸ˜†

slate swan
#

im joking its alrpithink

slate swan
#

no no you didnt

#

its just shorter lol

#

oh wait @spring flax dont use that thats like ctx.send yours better because your sending a response msg with interaction so thats my fault

spring flax
#

what do you mean?

#

you mean to use await inter.response.send_message(embed=embed)?

slate swan
#

yes

spring flax
#

what's the difference?

slate swan
#

if your using .send() the coro it doesnt have ephemeral but inter.response.send_message as it says responds to a interaction and does have the ephemeral kwarg so im sorry for that

spring flax
#

i'm pretty sure inter.send(**kwargs, ephemeral=True) works too

slate swan
#

oh yeah its a interaction attr so it probably doesπŸƒ

spring flax
#

yeah just tried

slate swan
#

well yes then it doesπŸƒ

spring flax
#

also, can suggest some application user commands?

slate swan
#

an avatar command is good

#

and a info command (info about the account)

spring flax
#

how do i do message commands by the way?

slate swan
#

msg commands by?

spring flax
#

application message commands * my bad

slate swan
#

so like slash commands that sends a msg?

spring flax
#

it's not on the examples on the github

slate swan
#

well its just like any command

#

in this case interaction is your context which i think interaction has all of the attrs of it

quartz badger
#

I have this command and every 20 minutes it sends a new message telling me the correct time on a specific channel. How do I make it so that instead of every 20 minutes it would send a new message, it would edit the message it sent to put the new time?

@commands.Cog.listener()
    async def on_ready(self):
        self.current_time.start()

    @tasks.loop(minutes=20) 
    async def current_time(self):

        now = datetime.datetime.now()
        now = now.strftime("%d/%m/%Y Γ s %H:%M:%S")

        channel = self.bot.get_channel(914569334985216060)

        await channel.send("Data atual: " + now)```
spring flax
#

how do I DM a user with disnake's application commands?

spring flax
#

it's a disnake message application command

slate swan
#

!d disnake.Client.get_message

unkempt canyonBOT
slate swan
#

for disnake ^

#

probably the same in dpy

vale wing
slate swan
#

interaction has an author attr use it

#

inter.author.send()

vale wing
#

I think he wants to dm message's author

#

Why would he need to dm himself lol

slate swan
#

so for a bookmark i suppose

dusk trout
#
import discord
from discord.ext import commands
from discord import DMChannel

mid = "550370780245000200"
bot = commands.Bot(command_prefix=".", description="Test")


@bot.command(name='dmsend', pass_contect=True)
async def dmsend(ctx):
    user = await bot.fetch_user(mid)
    await DMChannel.send(user, "Test")

@bot.command()
async def replace(ctx):
    return "didnt work"
mid = replace()
print(mid)




bot.run
vale wing
#

Oh

dusk trout
#

Why doesnt my second function redefine mid

slate swan
vale wing
#

pass_contect typo just saying

slate swan
#

isnt that deprecated as well

#

What's the function to kick a member from a channel?

vale wing
#

It's pointless afaik it's set to True by default

vale wing
slate swan
#

no such thing

slate swan
#

Like remove a member from a channel

dusk trout
#

now I get this error

keen talon
vale wing
#

You could set send messages permission to false that's the only thing I can think of

dusk trout
#

RuntimeWarning: coroutine 'Command.call' was never awaited
ret = await coro(*args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
<coroutine object Command.call at 0x000002176D2EE2C0>

slate swan
slate swan
slate swan
#

But nevermind, thanks

#

πŸ§β€β™‚οΈ

slate swan
vale wing
#

@slate swan you mean thread?

keen talon
slate swan
dusk trout
#

if i await mid=replace than it says cant await that function

vale wing
slate swan
vale wing
slate swan
dusk trout
vale wing
keen talon
slate swan
keen talon
slate swan
#

learn async programming pithink

keen talon
vale wing
slate swan
dusk trout
#

okay but is there any simplier I can make a command to redefine mid

vale wing
slate swan
keen talon
#

Btw u can't call a command like that ig

vale wing
#

!d disnake.ThreadMember

slate swan
unkempt canyonBOT
#

class disnake.ThreadMember```
Represents a Discord thread member.

x == y Checks if two thread members are equal.

x != y Checks if two thread members are not equal.

hash(x) Returns the thread member’s hash.

str(x) Returns the thread member’s name.

New in version 2.0.
dusk trout
slate swan
dusk trout
#

like how would I make it a command

vale wing
#

@slate swan ok found it

#

!d disnake.Thread.remove_user

unkempt canyonBOT
#

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

Removes a user from this thread.

You must have [`manage_threads`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.manage_threads "disnake.Permissions.manage_threads") or be the creator of the thread to remove a user.
slate swan
unkempt canyonBOT
#

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

001 | lol
002 | lmao
slate swan
#

basic pypithink

slate swan
vale wing
#

Btw if I want to set up voting rewards for top.gg do I really need to build whole API responsible for receiving requests from them (cause I made it but maybe there's an easier method waitwhat)

keen talon
#

U can use a webhook

#

Ig

vale wing
#

Webhook on bot's edit page?

#

I only used it for API purpose

dusk trout
#
import discord
from discord.ext import commands
from discord import DMChannel

mid = "550370780245000200"
bot = commands.Bot(command_prefix=".", description="Test")


@bot.command(name='dmsend', pass_contect=True)
async def dmsend(ctx):
    user = await bot.fetch_user(mid)
    await DMChannel.send(user, "Test")

@bot.command()
async def function(ctx):
    print(mid)
    await function()



bot.run
vale wing
#

Like it sends POST req to my API and it does the stuff

dusk trout
#

did I do something wrong

keen talon
#

I didn't read the api yet lol

slate swan
#

Also, how do I create a thread? I've tried looking through discord.Guild methods but can't find anything Oh nevermind, it must be a TextChannel method

vale wing
#

That wouldn't work

#

Why do you call function from inside the function?

slate swan
keen talon
slate swan
keen talon
#

Oh

#

I was looking at the first

slate swan
dusk trout
#
import discord
from discord.ext import commands
from discord import DMChannel

mid = "550370780245000200"
bot = commands.Bot(command_prefix=".", description="Test")


@bot.command(name='dmsend', pass_contect=True)
async def dmsend(ctx):
    user = await bot.fetch_user(mid)
    await DMChannel.send(user, "Test")

@bot.command()
async def function(ctx):
    int = mid
    print(int)
    await function()



bot.run
keen talon
#

I am doing everything stupidly today

dusk trout
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: function() missing 1 required positional argument: 'ctx'

dusk trout
slate swan
vale wing
#

Man don't call function from function

keen talon
vale wing
#

You don't need recursion trust me also you didn't provide ctx

slate swan
#

and why are you setting int to a var?

dusk trout
#

I NEED A BOT COMMAND to reset it

#

like bro

keen talon
#

@dusk trout when did u learn python

vale wing
#

Uh?

dusk trout
#

how do I get it into an async def format

keen talon
#

!d discord.DMChannel

unkempt canyonBOT
#

class discord.DMChannel```
Represents a Discord direct message channel.

x == y Checks if two channels are equal.

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

hash(x) Returns the channel’s hash.

str(x) Returns a string representation of the channel
slate swan
#

how is setting a var value so hardpithink

keen talon
#

@slate swan can I know where you are from

vale wing
#

@dusk trout please tell me what do you expect your function command to do

dusk trout
keen talon
slate swan
keen talon
vale wing
keen talon
#

Maybe globals

dusk trout
#

yes so like .replace 10 and mid becomes 10

#

.function 10

vale wing
#

Oh

#
@bot.command()
async def replace(ctx, new_value: int):
    global mid
    mid = new_value```
#

Maybe this is what you meant?

slate swan
keen talon
#

@dusk trout reply to me man , when did ya learn python

dusk trout
keen talon
slate swan
vale wing
keen talon
vale wing
#

It's very complicated trust me

dusk trout
#

Yeah but I am trting to becoem a developer somewhere and this is like their minimum

slate swan
dusk trout
#

thanks πŸ™‚

slate swan
#

i belive in youpithink

keen talon
#

All the best πŸ‘

slate swan
#

yup

vale wing
#

Like personally I got to developing bots after getting enough knowledge about python and even after doing some stuff in pyqt 9839megaflushed

keen talon
slate swan
vale wing
#

Actually now I forgot everything about pyqt 😩

vale wing
#

I only remember something like

#

Triggers?

slate swan
vale wing
#

Maybe I should learn it again

keen talon
#

You had no guide ig

slate swan
#

yeah

vale wing
#

Me?

keen talon
vale wing
#

Oh lol

slate swan
#

most people here are self thought

keen talon
# slate swan yeah

Don't try to learn something just because u want to learn it at the moment lol

#

πŸ˜† πŸ˜†

dusk trout
keen talon
#

U should learn other basic topics related to it

keen talon
keen talon
#

You are a huge pika fan ig

slate swan
keen talon
#

Can I dm ?

slate swan
keen talon
slate swan
spring flax
#

does message attachments fall under message content?

vale wing
#

Currently I want to learn AI and when I see tensorflow examples I am like wtf is this

slate swan
keen talon
#

πŸ˜† πŸ˜†

vale wing
#

Library for machine learning

#

I wonder if

slate swan
#

pretty cool

keen talon
vale wing
#

Nvm I don't even remember it

vale wing
keen talon
#

πŸ˜†

vale wing
#

😩

keen talon
#

Bye

#

Cya πŸ‘‹πŸ‘‹πŸ˜

vale wing
#

Bye have a nice day

slate swan
#

How do I get a list of messages in a channel? I know channel.history exists so I tried channel.history().messages but I don't think it's right or maybe I'm doing something wrong?

potent spear
boreal ravine
#

Only the message attachments

knotty cedar
#

Can anyone help me?

boreal ravine
#

sure, what is it?

knotty cedar
#

dm?

#

@boreal ravine

boreal ravine
#

uh

#

i dont dm help 😢

knotty cedar
#

it is of replit

boreal ravine
polar ice
#

The code im trying to seperate are just async functions

slate swan
knotty cedar
polar ice
#

@slate swanIll take a look using cogs, never used them before πŸ˜„

slate swan
unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
#

yeah i think you can

slate swan
slate swan
knotty cedar
slate swan
knotty cedar
slate swan
knotty cedar
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.

knotty cedar
slate swan
#

ik but i dont want to do it for youpithink

#

we help here not do it for youpithink

knotty cedar
slate swan
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.

knotty cedar
#

!code

slate swan
#

embed =discord.Embed()

#

not so

knotty cedar
#

@slate swan here it is

slate swan
#

use the coding format

knotty cedar
slate swan
#

@slate swan pic = discord.Embed().embed.set_image(url="https://toughlittlebirds.files.wordpress.com/2014/05/duckling_mallard_pieter_pieterse.jpg")

knotty cedar
#

@slate swan

dusk trout
#

this is a stupid question but how do I make my bot repeat it slef non stop

#

so loop

slate swan
#

this is a python server?

honest lintel
#

Hey, I've got a simple question
client.get_all_members() doesn't seem to refresh in my while loop. How can I update it's content?

knotty cedar
quaint epoch
#

could you do py await ctx.author.send('direct_message')?

slate swan
quaint epoch
#

i should've done that before fetching the authors id

slate swan
#

lol

knotty cedar
honest lintel
# vale wing Uh could you show your code?
@client.event
async def on_ready():
    status18 = status24 = False
    while True:
        for member in client.get_all_members():
            # Rortox
            if member.id == 575326754214903818:
                status18 = handle_gpio(member, status18, 18)
            # The Creator
            if member.id == 395614306496020500:
                status24 = handle_gpio(member, status24, 24)
        time.sleep(5)
#

The member list and all member status information doesn't change when calling client.get_all_members

vale wing
#

I am not sure if you really need this code construction, you could just get_user?

honest lintel
#

You're right, thanks, I'll try this

vale wing
#

Depends on what's inside of your handle_gpio function, it should be like

status18 = handle_gpio(client.get_user(id1), status18, 18) #etc```
#

If your function requires Member and not User, you might want to get the corresponding instance

honest lintel
vale wing
#

Could you show your handle_gpio function if you don't mind?

honest lintel
#
def handle_gpio(member, status, pin):
    # initialize status
    new_status = status
    if member.status.name != "offline" and not status:
        print("Debug: Outputting True")
        GPIO.output(pin, True)
        new_status = True
    elif member.status.name == "offline" and status:
        print("Debug: Outputting False")
        GPIO.output(pin, False)
        new_status = False
    return new_status
vale wing
#

You don't need Member ig

#

You could just parse User that you get from client.get_user

honest lintel
#

But User doesn't have a status attribute

vale wing
#

Doesn't it?

#

Oh you are right

#

Hold up imma try to resolve this

honest lintel
#

Thanks man

vale wing
#

@honest lintel if there's a guild they both certainly belong to, you could use

client.get_guild(that_guild_id).get_member(id1)```
to get the Member instance, otherwise
```py
client.get_guild(client.get_user(id1).mutual_guilds[0].id).get_member(id1)```
but it is more complicated and I don't think it is right way
honest lintel
#

Yes, I want to do that in a private server where both will be. Thanks, I'll try the first one.

dusk trout
#

hey @vale wing how can I make my code loop non stop

unkempt canyonBOT
#

Hey @dusk trout!

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

vale wing
#

Like

while True: #or while 1
    print('Hello')```
However infinite loops are bad practice in most of cases. What do you want to loop exactly?
dusk trout
#

bruh

tall ibex
#

while (variable name) == False:

#

oh

velvet tinsel
dusk trout
#
import discord
import time
from discord.ext import commands
from discord import DMChannel



while True:
    loop
#

?\

vale wing
tall ibex
#

yh

dusk trout
#

loop = loop.loop

#

was it?

vale wing
#

Sorry I don't quite understand you 😁

tall ibex
#

^

dusk trout
#

what should I define loop as

vale wing
#

First step of creating a code is state what do you expect your code to do

#

So what do you want the program to do

dusk trout
#

I just want it to do loop my code below

#

I couldnt send it here

#

its too long

vale wing
#

Use pastebin

#

It really matters what you loop and how you loop it in async app. If you loop sending message you will most likely get ratelimited

dusk trout
#
import discord
import time
from discord.ext import commands
from discord import DMChannel


loop =
while True:
    loop

mid = "342036584650113045"
tid = "Insert Id here"
wid = "Insert ID here"
thid = "Insert ID here"
fid = "Insert id here"
suid = "Insert ID here"
satid = "Insert ID here"
bot = commands.Bot(command_prefix=".", description="Test")


@bot.command(name='dmsend', pass_contect=True)
async def dmsend(ctx):
    mon = await bot.fetch_user(mid)
    tue = await bot.fetch_user(tid)
    wed = await bot.fetch_user(wid)
    thur = await bot.fetch_user(thid)
    fir = await bot.fetch_user(fid)
    said = await bot.fetch_user(satid)
    sunid= await bot.fetch_user(suid)

    await DMChannel.send(sunid, "This is a friendly reminder to do your QOTD")
    await time.sleep(86400)
    await DMChannel.send(mon, "This is a friendly reminder to do your QOTD")
    await time.sleep(86400)
    await DMChannel.send(tue, "This is a friendly reminder to do your QOTD")
    await time.sleep(86400)
    await DMChannel.send(wed, "This is a friendly reminder to do your QOTD")
    await time.sleep(86400)
    await DMChannel.send(thur, "This is a friendly reminder to do your QOTD")
    await time.sleep(86400)
    await DMChannel.send(fir, "This a friendly reminder to do your QOTD")
    await time.sleep(86400)
    await  DMChannel.send(said, "This is a friendly reminder to do your QOTD")


@bot.command()
async def replacemon(ctx, new_value: int):
    global mid
    mid = new_value



@bot.command()
async def replacetue(ctx, new_value: int):
    global tid
    tid = new_value


@bot.command()
async def replacewed(ctx, new_value : int):
    global thid
    thid = new_value
#

something like this

#

its goes on longer but

#

I want this to repeaty

vale wing
#

Oh

#

There's a better thing for this

#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
vale wing
#

^

honest lintel
#

Ok, now I'm back at my first issue. It looks like client is some kind of snapshot and represents the state of the guild on initialization.
That means that the Member.status doesn't update in my program when I change it in Discord.
Is there a way to refresh the client so it contains up-to-date Member-data?

vale wing
#

@honest lintel how do you define client?

honest lintel
#

client = discord.Client(intents=intents)

vale wing
#

Wrong way

#

Use subclass of Client which is Bot:

client = commands.Bot(intents=intents)```
And better rename the variable to `bot`
#

Maybe that's what's causing your issue

honest lintel
#

Ok, thanks

vale wing
#
from discord.ext import commands```
honest lintel
#

The status still doesn't update :(

#

That's my full code now.

import os

import RPi.GPIO as GPIO
import discord
from discord.ext import commands
from dotenv import load_dotenv

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)

load_dotenv()

TOKEN = os.getenv("BOT_TOKEN")

intents = discord.Intents.all()

description = "isOnline Bot"

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


def handle_gpio(member, status, pin):
    # initialize status
    new_status = status
    if member.status.name != "offline" and not status:
        print("Debug: Outputting True")
        GPIO.output(pin, True)
        new_status = True
    elif member.status.name == "offline" and status:
        print("Debug: Outputting False")
        GPIO.output(pin, False)
        new_status = False
    return new_status


@bot.event
async def on_ready():
    status18 = status24 = False
    while True:
        rortox = bot.get_guild(928999025708003338).get_member(575326754214903818)
        the_creator = bot.get_guild(928999025708003338).get_member(395614306496020500)
        status18 = handle_gpio(rortox, status18, 18)
        status24 = handle_gpio(the_creator, status24, 24)


bot.run(TOKEN)

vale wing
#

@honest lintel the status that is not updated is member.status?

honest lintel
#

Yes. eg rortox.status doesn't change on iterations, even though I changed it in Discord.

vale wing
#

And I think it would be a better practice to compare like

if member.status != discord.Status.offline``` iirc
light night
vale wing
#

@honest lintel hold up I see what's wrong now

vale wing
#

Infinite loop in on_ready which causes you to have ratelimit

#

You make requests to discord API too often ig

#

You could move it to external loop with certain interval

#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
vale wing
#

If you need usage example feel free to ask me but I think there is one

honest lintel
#

I actually debugged it and only iterated a few times over the loop, always waiting a few seconds, so I don't think this is the issue. But that's a good idea for when I'll actually use it.

vale wing
honest lintel
# vale wing Yeah waiting after each iteration is what you needed. Actually you need to use t...
import os
import time

import RPi.GPIO as GPIO
import discord
from discord.ext import commands, tasks
from dotenv import load_dotenv

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)

load_dotenv()

TOKEN = os.getenv("BOT_TOKEN")

intents = discord.Intents.all()

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


def handle_gpio(member, pin):
    if member.status.name != discord.Status.offline:
        print("Debug: Outputting True")
        GPIO.output(pin, True)
    elif member.status.name == discord.Status.offline:
        print("Debug: Outputting False")
        GPIO.output(pin, False)


@bot.event
async def on_ready():
    update_online_status.start()
    print("Started bot")


@tasks.loop(seconds=10)
async def update_online_status():
    rortox = bot.get_guild(928999025708003338).get_member(575326754214903818)
    the_creator = bot.get_guild(928999025708003338).get_member(395614306496020500)
    handle_gpio(rortox, 18)
    handle_gpio(the_creator, 24)


bot.run(TOKEN)

#

Does this look better?

vale wing
#

Move start function to on_ready

honest lintel
#

ok

vale wing
#

And increase the interval

#

I would suggest to put at least 30 seconds for this case

honest lintel
#

Wow, it started updating everything now! Thanks you so much @vale wing , I wonder why you're not a Helper yet

honest lintel
vale wing
#

Because I got to here not far ago

#

You are welcome 😁

honest lintel
#

That's what I was trying to do. Whenever my friend gets online, the light will turn on.

vale wing
#

Oh raspberry pi nice thing

#

I actually did some projects on arduino

honest lintel
#

Cool! What did you do?

vale wing
#

LEDs blinking CURSEDHAHA

#

Jk

#

I actually tried some analog input, temperature metrics and other simple projects, currently I am working on door access control system and still waiting for the materials to arrive to actually build it

honest lintel
#

That sounds very useful

#

and complicated

vale wing
#

The thing that might be complicated is SPI interface, that's the only I am worried about. But I hope I will be able to figure it out 😁

honest lintel
#

Good luck!

vale wing
#

Thanks, good luck you too

honest lintel
#

Thank you!

honest lintel
vale wing
#

discord.Status is an enumerator

#

If you want to compare it with a string, you should use its name attribute

discord.Status.offline.name```
#

!d enum.Enum

unkempt canyonBOT
#

class enum.Enum```
Base class for creating enumerated constants. See section [Functional API](https://docs.python.org/3/library/enum.html#functional-api) for an alternate construction syntax.
vale wing
#

Iirc status inherits it

honest lintel
#

Ok, I was confused because discord.Status.offline is a String. I guess it's just some metaclass stuff going on. Thanks

vale wing
#

!e

from enum import Enum

class MyStatus(Enum):
    offline = 0
    online = 1

print(MyStatus.offline == MyStatus.offline)```
Basically works like this
unkempt canyonBOT
#

@vale wing :white_check_mark: Your eval job has completed with return code 0.

True
slate swan
#
# ADD - BLACKLIST =================================================================================== Fortu'Neko#2987 ==
    @blacklist.command()
    async def add(self, ctx, user: discord.Member = "none"):

        with open("./data/moderators.json", "r") as f:
            moderators = json.load(f)

        if ctx.author.id in moderators:

            if user == "none":

                em1 = discord.Embed(title=f":warning: Warning",
                                    description=f"{ctx.author.mention}, you've to mention that person.",
                                    color=col_warn)

                await ctx.send(embed=em1)

            else:

                with open("./data/blacklist.json", "r") as f:
                    blacklist = json.load(f)

                if user.id in blacklist:

                    em2 = discord.Embed(title=f":warning: Warning",
                                        description=f"{user.mention} is already blacklisted.",
                                        color=col_warn)

                    await ctx.send(embed=em2)

                else:

                    em3 = discord.Embed(title=f":white_check_mark: Successful",
                                        description=f"{user.mention} has been blacklisted.",
                                        color=col_success)

                    blacklist = user.id

                    with open("./data/blacklist.json", "w") as f:
                        json.dump(blacklist, f)

                    await ctx.send(embed=em3)

        else:

            em4 = discord.Embed(title=f":no_entry: Error",
                                description=f"{ctx.author.mention}, you're not a moderator!",
                                color=col_error)

            await ctx.send(embed=em4)

blacklist.json
Before

[]```
After
```py
123456789000```
Without `[]`, what's wrong with that?
honest lintel
vale wing
#

Yeah

#
blacklist = user.id```
#

Perhaps you meant

blacklist.append(user.id)```?
slate swan
#

@-@ have I to int it?

#

nah

vale wing
#

user.id is already an int

slate swan
#

yea

vale wing
#

Just add it to the list

hushed rain
#

Ill pay someone $5 cashapp to help me get this bot working

slate swan
#

ty xD

vale wing
vale wing
slate swan
vale wing
#

Imho it's easier to use

slate swan
#

also

vale wing
#
@bot.command()
@commands.has_role(some_role_id)
async def cmd(...```
slate swan
#

it isnt working on a role

vale wing
#

How tho?

slate swan
#

It's all about a userID in a json file

vale wing
#

Oh

hushed rain
# vale wing I don't need payment but could you show your code here?

Yes, here it is. ```py
import requests
import json
from requests.models import ContentDecodingError

Format Sent

while True:
headers = {
'authorization': ''
}
# Request from Discord with headers
r = requests.get(f'https://discord.com/api/v9/channels/883204140279414794/messages', headers=headers)
# Print Request
jsonn = json.loads(r.text)

for value in jsonn:

    message = (value['content'], '\n')
    print(value, '\n')

# Discord Send Message
payload = {
    'content': message
}

header = {
    'authorization': ''
}

r = requests.post("https://discord.com/api/v9/channels/883204140279414794/messages", data=payload, headers=header)
break

if message == 'content':

False
vale wing
#

Then you need a custom check, I can explain them to you

slate swan
#

moderator.json
[uID, uID]

#

blacklist.json is the same thing ^^

hushed rain
vale wing
hushed rain
vale wing
#

Oh so you just couldn't install the library?

hushed rain
vale wing
#

So you mean send message in one server and then the bot will send it to others?

hushed rain
#

Exactly

#

I need it to find a specific format of content and post it to another channel

vale wing
#

@slate swan if all the commands in the cog require author to be the mod, there's a simple trick to get rid of the if statements in every command, also it increases code readability

#

@hushed rain have you tried doing it with discord.py?

#

Or just couldn't figure it out at all

hushed rain
vale wing
#

Oh

#

You installed it with pip?

hushed rain
slate swan
#

lmao xD

vale wing
vale wing
#

Or gave some errors

slate swan
hushed rain
vale wing
# slate swan what kind?
def is_mod():
    def subf(ctx):
        return ctx.author.id in moderators

    return commands.check(subf)```
boreal osprey
#

im trying to install dotenv again

vale wing
#

And then you can decorate functions with @is_mod()

vale wing
boreal osprey
#

help im stuck on trying to download dotenv

hushed rain
vale wing
#

Um

#

Could you show the full error?

boreal osprey
#

who

hushed rain
#

ModuleNotFoundError: No module named 'discord'

vale wing
hushed rain
vale wing
#

Code editor

hushed rain
#

visual studio code

vale wing
#

And you run the script from there right?

hushed rain
#

Yes, from the terminal inside the IDE

vale wing
#

Do you have python extension installed?

slate swan
boreal osprey
#

why am i stuck on this

vale wing
#

@boreal osprey try running it like this, not sure if it will help
pip install dotenv --no-cache-dir

slate swan
north summit
#

Can anyone help me with replit

north summit
vale wing
slate swan
vale wing
#

And outer function returns commands.check with subfunction as a parameter

slate swan
#

xD

north summit
vale wing
#

Usually it would raise CheckFailure if you don't raise another exception

slate swan
# vale wing Perhaps you meant ```py blacklist.append(user.id)```?
                if user.id in blacklist:

                    em2 = discord.Embed(title=f":white_check_mark: Successful",
                                        description=f"{user.mention} has been removed from the blacklist.",
                                        color=col_success)

                    blacklist.pop(user.id)

                    with open("./data/blacklist.json", "w") as f:
                        json.dump(blacklist, f)

                    await ctx.send(embed=em2)
```What about that? it isn't removing
#

pop index out of range

vale wing
#

You need to remove the item, not the item by index

#

Bro

slate swan
#

.-.

cedar stream
#

!type

#

!d type

unkempt canyonBOT
#

class type(object)``````py

class type(name, bases, dict, **kwds)```
With one argument, return the type of an *object*. The return value is a type object and generally the same object as returned by [`object.__class__`](https://docs.python.org/3/library/stdtypes.html#instance.__class__ "instance.__class__").

The [`isinstance()`](https://docs.python.org/3/library/functions.html#isinstance "isinstance") built-in function is recommended for testing the type of an object, because it takes subclasses into account.
cedar stream
#

πŸ€·πŸΌβ€β™‚οΈ

vale wing
#

@slate swan list.pop removes an element by index, you need list.remove to remove the item itself

#

!e

help(list.remove)```
#

Nice protection

cedar stream
vale wing
#

^ just know the difference between pop and remove for lists

cedar stream
cedar stream
#

Np

slate swan
#

@vale wing ty u2

vale wing
#

Np

silver magnet
#

I'm trying to make a ping feature for a bot i'm making, but i dont know how to make it say both the latency and the string.
if msg.startswith(";ping"): await message.channel.send("In miliseconds:" {round(client.latency * 1000)}) return

cedar stream
#

F string

silver magnet
#

I need to put something in the middle and connect them, but what?

cedar stream
#

Use f string

silver magnet
#

oh yeah that exists

#

I've seen you have to use a + after adding the f but it doesn't seem to work. The error:
SyntaxError: invalid syntax

#

So there's an invalid syntax.

#

i guess

cedar stream
#

Lemme rq

#

Read that

silver magnet
#

thank you so much

flat solstice
#

Is there a way to identify who invited a bot? I'm making a greeting msg for new users and I don't want it to greet bots (which I know how to do) but I want it to also send a msg in my staff commands saying which user invited the bot which is why I'm confused, does it work in the same way as normal member invite tracking or is there something else?

slate swan
#

Is this correct?

@commands.has_permissions(kick_members=True)
silver magnet
#

Is there a way to make the bot read the rest of an message after the command was sent?

flat solstice
# silver magnet audit log?

oh yeah I can get my bot to read that, How do I filter that tho to get what I'm looking for as I've not dabbled with getting bots to check audit logs before

silver magnet
#

it shows who creates the bot roles and its perms

potent spear
#

probably that, yeah

slate swan
#

I'm guessing that's what you asking for

silver magnet
potent spear
silver magnet
#

ah. necessary to create a new client event?

potent spear
#

when you do ?cmd I shat yesterday
then arg will be equal to I shat yesterday

slate swan
#

No

#

yeah

#

So something like this

@bot.command()
async def repeat(ctx,*,message):
  await ctx.message.delete()
  await ctx.send(message)
#

Whatever you say after repeat will be what the bot repeats

potent spear
#

correct

marsh depot
#

Hi anyone know how can i edit a embed image making a command

potent spear
#

you have to be aware of some stuff, like this will throw errors etc if you just type ?repeat for example

slate swan
#

Yeah

marsh depot
#

im making this code , it works in TextMessages but not in embes

@bot.command()
async def edit_gif(ctx, msg_id : int = None, channel: discord.TextChannel = None, *, link=None):
  if not msg_id:
    await ctx.reply(f"Tienes que agregar la ID del mensaje que quieras editar")
    return
  elif not channel:
    await ctx.reply(f"Tienes que agregar el canal done se encuentra mensaje que quieras editar")
    return
  elif not message:
      await ctx.reply(f"Tienes que agregar el mensaje que quieras poner para editar")
      return
  msg = await channel.fetch_message(msg_id)
  new_embed = discord.Embed(title='\n', description='\n', color=0xff261b)
  new_embed.set_image(url=f"{link}") # I try to write url=link and still don't work
  await msg.edit(embed=new_embed)
potent spear
silver magnet
#

most of the time i make strings with the prefix so I don't really know how it's like

slate swan
#

Yeah just change the command name

silver magnet
#

ahh

slate swan
#

after async def

potent spear
#

you can have aliases...

slate swan
#

yeah or have aliases

silver magnet
#

"Unresolved reference 'bot'"

slate swan
#

🀦

#

are you using client

silver magnet
#

yeah

slate swan
#

Then change bot to client on the first line

marsh depot
silver magnet
#

please dont be stressed im just veery new lol

slate swan
#

Can I still follow this video of db’s if I use replit? Cuz he makes a table https://youtu.be/Y9DzfPJsP2s

My discord server β–Ί https://discord.gg/sfYjTSA
(If you have any questions or just want to have a chat with us)

(Some Cool Stuff)
Nertivia β–Ί https://nertivia.supertiger.tk/
My server in Nertivia β–Ί https://nertivia.supertiger.tk/invites/B4tMwO

Install discord.py β–Ί pip install discord.py or py -3 pip install discord.py
Discord.py documentation β–Ί...

β–Ά Play video
frail notch
#

can someone lmk if you're familiar with oauth2 exchange codes and how they are generated

slate swan
slate swan
marsh depot
#

Nothing still don't working

slate swan
#

Show your code?

slate swan
marsh depot
# slate swan Show your code?
@bot.command()
async def edit_gif(ctx, msg_id : int = None, channel: discord.TextChannel = None, *, link=None):
  if not msg_id:
    await ctx.reply(f"Stuff")
    return
  elif not channel:
    await ctx.reply(f"Stuff")
    return
  elif not message:
      await ctx.reply(f"Stuff")
      return
  msg = await channel.fetch_message(msg_id)
  new_embed = discord.Embed(title='\n', description='\n', color=0xff261b)
  new_embed.set_image(url=link) # I try to write url=f"{link}" and still don't work
  await msg.edit(embed=new_embed)

I make the command like these, for make it you need to put
!edit_gif messageID channelMention NewLink

potent spear
#

there's no need for the link to have *, in front

#

because it's one word, not really a string with spaces

#

also, what you did in comments, please keep it like that

flat solstice
potent spear
#

your link is standard a string, dont do f"{link}", that's useless

marsh depot
marsh depot
hushed rain
#

Challenge Question
How would you change the code to find the value of ['author'] inside of ['username']

for value in jsonn:
    message = (value['content'], value['username'], '\n')
potent spear
marsh depot
potent spear
marsh depot
#

i send a Embed and want to edit gif 2 min later for example

potent spear
marsh depot
slate swan
#

Iterable command_prefix or list returned from get_prefix must contain only strings, not function

client = commands.Bot(command_prefix=["$", get_prefix], help_command=None)
slate swan
potent spear
#

if it's not found, return the standard one

hushed rain
silver magnet
#

i have a problem with using ctx. everytime i try making a command with it it doesn't work while with something like message.channel.send it works.

slate swan
potent spear
potent spear
hushed rain
# potent spear show me a piece of json and tell me what you need, I'll tell you

This is the json @potent spear πŸ™‚

{'id': '929143642432626750', 'type': 0, 'content': 'This Message Was Sent with Python', 'channel_id': '883204140279414794', 'author': {'id': '196079195376451584', 'username': 'Ike P', 'avatar': '766de912475c7d057cb37f61f75f0f55', 'discriminator': '6874', 'public_flags': 0}, 'attachments': [], 'embeds': [], 'mentions': [], 'mention_roles': [], 'pinned': False, 'mention_everyone': False, 'tts': False, 'timestamp': '2022-01-07T22:45:07.010000+00:00', 'edited_timestamp': None, 'flags': 0, 'components': []}
slate swan
#

mine is working

hushed rain
silver magnet
potent spear
hushed rain
# potent spear data = yourjsonshit `your_username= data['author']['username']`

Returns

{'id': '929143461473579029', 'type': 0, 'content': 'hello', 'channel_id': '883204140279414794', 'author': {'id': '196079195376451584', 'username': 'Ike P', 'avatar': '766de912475c7d057cb37f61f75f0f55', 'discriminator': '6874', 'public_flags': 0}, 'attachments': [], 'embeds': [], 'mentions': [], 'mention_roles': [], 'pinned': False, 'mention_everyone': False, 'tts': False, 'timestamp': '2022-01-07T22:44:23.866000+00:00', 'edited_timestamp': None, 'flags': 0, 'components': []}
hushed rain
#

Actually, was able to make it work! Thank you πŸ™

slate swan
#
{
  'id': '929143642432626750',
  'type': 0,
  'content': 'This Message Was Sent with Python',
  'channel_id': '883204140279414794',
  'author': {
    'id': '196079195376451584',
    'username': 'Ike P',
    'avatar': '766de912475c7d057cb37f61f75f0f55',
    'discriminator': '6874',
    'public_flags': 0
  },
  'attachments': [],
  'embeds': [],
  'mentions': [],
  'mention_roles': [],
  'pinned': False,
  'mention_everyone': False,
  'tts': False,
  'timestamp': '2022-01-07T22:45:07.010000+00:00',
  'edited_timestamp': None,
  'flags': 0,
  'components': []
}
#

more overview

hushed rain
#

I was able to get it with

print(value['author']['username'],":", value['content'])
hushed rain
potent spear
silver magnet
#

anyone can help with ctx problems? just asking

potent spear
silver magnet
slate swan
silver magnet
#

i tried running the code
@client.command()
async def repeat(ctx,*,message):
await ctx.message.delete()
await ctx.send(message)

#

it didn't give a response

potent spear
#

your client has to be defined like this

potent spear
#

client = commands.Bot(...)

silver magnet
#

ah

potent spear
#

not like this client = discord.Client(...)

silver magnet
#

mine is discordClient()

#

ohhh

potent spear
#

commands.Bot has all the functionality discord.Client has + commands and tasks

slate swan
#
import discord
from discord.ext import commands

client = commands.Bot(command_prefix="$")

@client.command()
async def repeat(ctx, *, message):
  await ctx.message.delete()
  await ctx.send(message)

client.run("TOKEN")
``` Command would be `$repeat <message>`
#

@silver magnet

silver magnet
#

understood

slate swan
#

I recommend you change the code to this to prevent people from pinging and to handle errors. @silver magnet

@client.command()
async def repeat(ctx, *, message=None):
  if message == None:
    await ctx.send("Arguement error")
  await ctx.message.delete()
  await ctx.send(f"`{message}`")
marsh depot
silver magnet
#

it still doesn't have input. I'm just very new to this.

potent spear
slate swan
#

There

potent spear
#

yup, that's it

slate swan
silver magnet
#

it's a bot i made for a private server

#

I could remove triggers and send the code here

#

oh yeah and ofc censor the token

slate swan
#

yeah send the code

wicked atlas
potent spear
#

he just has initialized his client wrong, that's all

silver magnet
#

just please dont laugh at me im veeery new lmaoo

quaint epoch
silver magnet
#
import discord
from discord.ext import commands
import random
import os


client = commands.Bot(command_prefix=";")

TOKEN = "no"


@client.event
async def on_ready():
    print("logged as {0.user}".format(client))


@client.event
async def on_message(message):
    username = str(message.author).split('#')[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username}: {user_message} ({channel})')

    if message.author == client.user:
        return


@client.event
async def on_message(message):
    if message.author == client.user:
        return

    msg = message.content

    if msg.startswith("5naf!ping"):
        await message.channel.send(f"In miliseconds: {round(client.latency * 1000)}")
        return

@client.command()
async def repeat(ctx, *, message):
  if not message:
    await ctx.send("Arguement error")
  await ctx.message.delete()
  await ctx.send(f"`{message}`")

client.run(TOKEN`)```
#

this is on PyCharm

potent spear
#

your on_message events are shadowing

slate swan
#

use a codeblock please lmfao

#

!codeblock

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

slate swan
#

Don't use events for commands

quaint epoch
#

never again

#

do py @client.command() async def foo(ctx, params): #do stuff here lol

silver magnet
#

problem is that like
ctx never worked for me for some weird ass reason

#

yes i have it installed

quaint epoch
silver magnet
#

yeah

#

i did the pip command in terminal

#

im using an ubuntu based distro

#

just to check

quaint epoch
#

don't import ctx

slate swan
#

@silver magnet fixed

import discord
from discord.ext import commands

client = commands.Bot(command_prefix=";")
TOKEN = "no"

@client.event
async def on_ready():
  print("logged as {0.user}".format(client))

@client.command()
async def ping(ctx):
  await ctx.send(f"In miliseconds: {round(client.latency * 1000)}")

@client.command()
async def repeat(ctx, *, message):
if not message:
  await ctx.send("Arguement error")
await ctx.message.delete()
await ctx.send(f"`{message}`")

client.run(TOKEN`)
silver magnet
#

woww

marsh depot
#

I put the GiF but dont change de url image of the embed

silver magnet
#

🀨

marsh depot
#

and no idea how to solve it

slate swan
#

run pip install discord in cmd

silver magnet
#

python 3.6 on PyCharm

#

weird

#

it's installed

slate swan
#

Did you just install it?

silver magnet
#

yeah

#

but i mean

#

i actually installed it in the beggining of the project

#

that i started just today

slate swan
#

you should update python aswell

silver magnet
#

any instructions on how to do it on linux?

quaint epoch
silver magnet
quaint epoch
#
@client.command()
async def repeat(ctx, *, message):
  if not message:
    await ctx.send("Argument error.")
    await ctx.message.delete()
    await ctx.send(f"`{message}`")```
silver magnet
#

ayy

#

well

#

none of the cmds seem to work

quaint epoch
#

and btw did you add your bot to the server with proper perms4

silver magnet
#

client = commands.Bot(command_prefix=";")
TOKEN = "imagine the token is here"


@client.event
async def on_ready():
  print("logged as {0.user}".format(client))


@client.command()
async def ping(ctx):
  await ctx.send(f"In miliseconds: {round(client.latency * 1000)}")


@client.command()
async def repeat(ctx, *, message):
  if not message:
    await ctx.send("Argument error.")
    await ctx.message.delete()
    await ctx.send(f"`{message}`")

client.run(TOKEN)```
#

why did it send 3 images

flat solstice
#

Can someone tell me where I'm going wrong with this, I don't seem to be getting errors but My bot just gets stuckpy async for entry in member.guild.audit_logs(action = discord.AuditLogAction.bot_add): print('{0.user}/{member} added {0.target}'.format(entry))

potent spear
flat solstice
potent spear
silver magnet
#

even the formatentry

#

p sure

#

or i just suck

#

πŸ‘

potent spear
#

just remove .format(entry)

#

you'll be left with
print(f"{entry.user} added {entry.target}")

#

welcome to the wonderful world of formatting strings

silver magnet
#

the bot says it's running but does nothing at all

potent spear
silver magnet
#

i think i just pressed ctrl v 3 times

#

lol

#

or are you not talking about the images

flat solstice
potent spear
silver magnet
#

huh

potent spear
silver magnet
#

ah

#

but why doesn't it run?

#

i mean it runs but no commands work

potent spear
#

full code?

potent spear
silver magnet
potent spear
silver magnet
#

yeah

#

i mean

potent spear
#

bruh, you're asking the wrong questions

silver magnet
#

the way i was doing it is apparently unefficient

potent spear
#

just ask "how do I run a command"

#

is your bot running and in your server?

silver magnet
#

im confused at this point

#

yeah its running

potent spear
#

and in a server you're in?

silver magnet
#

in the old script the commands worked fine

#

yeah

potent spear
#

alright

#

type ;ping

#

voila, it works, good luck with coding!

silver magnet
#

but in which code?

#

in this new one it doesn't seem to work

potent spear
#

in a channel on discord

#

just do it

silver magnet
#

i already did

#

with the new one

silver magnet
#

with the old one it worked, new doesn't

#

yeah the new one

potent spear
#

are you 100% certain you're running that file?

silver magnet
#

it doesn't give me any errors

#

in the run tab

potent spear
#

you're just running the wrong file I think

#

what IDE do you use?

silver magnet
#

PyCharm

potent spear
#

right click anywhere in the code

#

then run in terminal or whatever it says

#

also, stop running the previous code/ bot

silver magnet
#

ill try running it in the terminal

#

dammit my pc overheated again

#

@potent spear i ran in the terminal and the result was the same. It just said it was running.

silver magnet
#

:(

distant warren
silver magnet
#

client = commands.Bot(command_prefix=";")
TOKEN = "private"


@client.event
async def on_ready():
    print("logged as {0.user}".format(client))


@client.command()
async def ping(ctx):
    await ctx.send(f"In milliseconds: {round(client.latency * 1000)}")


@client.command()
async def repeat(ctx, *, message):
    if not message:
        await ctx.send("Argument error.")
        await ctx.message.delete()
        await ctx.send(f"`{message}`")


client.run(TOKEN)```
anything wrong with this code?
potent spear
#

yeah, the repeat command will never print anything

silver magnet
#

how can i?

potent spear
#

rest is fine

silver magnet
#

weird, the ping command never works

slate swan
#

hi guys im having trouble with this snipe command ```snipe_message_content = {}
snipe_message_author = {}

@commands.Cog.listener()
async def on_message_remove(self, message):
    global snipe_message_content
    global snipe_message_author

    await asyncio.sleep(30)

    snipe_message_author = {}
    snipe_message_content = {}



@commands.command()
async def snipe(self, ctx):
    channel = ctx.channel
    try:
        embed = discord.Embed(
            color = discord.Color.purple()
        )
        embed.set_author(name=f"Last deleted message in {ctx.channel.name}")
        embed.add_field(name="Author", value = {snipe_message_author})
        embed.add_field(name="Message: ", value = {snipe_message_content})
        await ctx.send(embed=embed)
    except:
        await ctx.send("There are no recently deleted messages!")
#

its only executing the bottom message

distant warren
#

I get AttributeError: 'NoneType' object has no attribute 'id' when defining guildide = message.guild.id

potent spear
distant warren
#

I just tried that and then you said it πŸ˜‚

#

wait lemme test it

potent spear
distant warren
#

works

potent spear
#

strange, since that's basically default...

silver magnet
#

asking again if something is wrong


client = commands.Bot(command_prefix=";")
TOKEN = "token stuff here"


@client.event
async def on_ready():
    print("logged as {0.user}".format(client))


@client.command()
async def ping(ctx):
    await ctx.send(f"In milliseconds: {round(client.latency * 1000)}")


@client.command()
async def repeat(ctx, *, message=None):
    if message is None:
        await ctx.send("Arguement error")
    await ctx.message.delete()
    await ctx.send(f"`{message}`")


client.run(TOKEN)```
for some reason, ctx never worked for me. Do I need to update my python?
potent spear
#

what version are you on?

#

python as well as dpy version pls

silver magnet
#

3.6

potent spear
#

import discord
print(discord.__version__)

silver magnet
#

1.7.3

quartz badger
#

I have this command to restart the bot and I was wondering if there was a way for the bot to send a message saying that it is back up and running in the chat that I did the command.

def restart_bot(): 
    os.execv(sys.executable, ['python'] + sys.argv)

@bot.command(name = 'restart')
async def restart(ctx):
    
    id = str(ctx.author.id)

    if id == '543955269315723279':
        await ctx.send("Estou a reiniciar... Aguarde um momento.")
        restart_bot()
  
    else:
        await ctx.send("VocΓͺ nΓ£o tem permissΓ£o para usar este comando!")```
potent spear
silver magnet
#

dpy is not downloaded i think because pip just downloaded it

quartz badger
potent spear
silver magnet
#

weird

potent spear
#

you can always store the channel_id in a db, and send to that channel on startup...

silver magnet
#

anything else you have to know?

#

or is it really a lost case

pliant gulch
#

This would be hard to do without a finiky method

#

And by finiky I mean some sort of flag passed for startup

potent spear
#

a startup task...

pliant gulch
#

Yes but then it would always send when the bot starts.

#

Not only after the bot gets restarted by the command

silver magnet
potent spear
#

if no value was found in the db => bot doesn't have to notify anyone

pliant gulch
potent spear
pliant gulch
#

Yes, every time the bot starts

#

I.e "startup task" am I wrong?

potent spear
#

mhm

pliant gulch
#

Yes, and so the bot can restart many times in it's lifetime

potent spear
#

the discord py server has genius tags/commands about this subject

potent spear
pliant gulch
#

Yes, so that would mean it doesn't run only once

potent spear
#

the startup task would only get invoked once, that's what matters ig

pliant gulch
#

Yes, per lifetime

potent spear
#

mhm

pliant gulch
#

A way to do this without a database is just to make a flag, you could overwrite run to take in another arg E.g run(TOKEN, restarted=True) and do stuff with that

potent spear
#

yeah, can perfectly be done in a config file

pliant gulch
#

This would mean you need specify something else in argv

silver magnet
#

i was using the wrong prefix all the time lol

#

now how do i make a certain command private for a channel?

#

trying to make a poll feature

async def poll(ctx, *, message=None):
    if message.channel == "mod-chat":
        if message is None:
            await ctx.send("Argument error")
        await ctx.message.delete()
        await ctx.send(f"@poll ping, `{message}`")
    else:
        return```
#

trying to make it only for the mods in the server

#

hence why the mod chat thing

pliant gulch
#

The message.channel == "mod-chat" part is wrong though

#

You are trying to compare a TextChannel to a str

#

Which will never be true

#

You meant to check name of message.channel

unkempt canyonBOT
silver magnet
pliant gulch
#

no

silver magnet
#

what do i need to do exactly?

silver magnet
#

ahhh

#

im still new to this, i only started like 2 days ago, can you explain if you don't mind?

#

since im still a bit confused

wicked atlas
silver magnet
#

i really am trying to learn from the things im doing wrong to get somewhere

wicked atlas
#

Then I would suggest you start by learning a few things about basic python, such as classes
https://www.w3schools.com/python/python_classes.asp

silver magnet
#

i know the veeery basics. What do i really need to change in the code?

wicked atlas
#

message.channel.name

silver magnet
#

i think i tried it be4 but ill see

#

well it still detects it as str

#

i tried using both () and ==

wicked atlas
#
if message.channel.name == "mod-chat":
    ...
silver magnet
#

i think ive tried that

#

AttributeError: 'str' object has no attribute 'channel'

#

it still detects it as str

#

i guess

wicked atlas
#

oh wait a

#

ok then, i did not read your code completely

#

message is a string. It's an argument for your command, so everything typed after your command will be put as a string into it

!myexamplecommand <everything here would be put into message>
#

You want to use ctx.message.channel, since ctx is the object that has the actual message object

silver magnet
#
async def poll(ctx, *, message=None):
    if ctx.message.channel == "mod-chat":
        if message is None:
            await ctx.send("Argument error")
        await ctx.message.delete()
        await ctx.send(f"@:clipboard: | Moderators, `{message}`")
    else:
        return```
#

is this good?

wicked atlas
#

and the .name

#

since you want the name of the channel

silver magnet
#

it worked ^^

#

how do i make it ping a role?

peak loom
#

No work.

#

I tried.

silver magnet
peak loom
#

Wait a minute...

#

Perfect i'll creae it into a command.

slate swan
#

Hello!

#
@client.command()
@commands.has_permissions(manage_messages=True)
async def welcome(ctx):
    guild = ctx.guild
    voice_client: discord.VoiceClient = discord.utils.get(client.voice_clients, guild = guild)

    while True:
        audio_source_list = [discord.FFmpegPCMAudio('file.mp3'), discord.FFmpegPCMAudio('clip2.mp3'), discord.FFmpegPCMAudio('clip3.mp3'), discord.FFmpegPCMAudio('clip5.mp3'), discord.FFmpegPCMAudio('clip6.mp3'), discord.FFmpegPCMAudio('clip7.mp3'), discord.FFmpegPCMAudio('clip9.mp3')]

        if voice_client.is_playing():
            continue

        else:
            voice_client.play(random.choice(audio_source_list), after = None)
            await asyncio.sleep(120)
#

@peak loom?

#

This code basically picks a random mp3 clip from the list and plays it. However, the bot only uses clip3, 5, and 9. It hasnt used File.mp3, or clip2.mp3, or the others

silver magnet
#

Is there any way I can make a bot add reactions to it's own message?

slate swan
#

Is there a way to prevent repetition unless the bot has used every clip in the list?

silver magnet
#

hm

slate swan
wicked atlas
#

!d random.shuffle

unkempt canyonBOT
#

random.shuffle(x[, random])```
Shuffle the sequence *x* in place.

The optional argument *random* is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function [`random()`](https://docs.python.org/3/library/random.html#random.random "random.random").

To shuffle an immutable sequence and return a new shuffled list, use `sample(x, k=len(x))` instead.

Note that even for small `len(x)`, the total number of permutations of *x* can quickly grow larger than the period of most random number generators. This implies that most permutations of a long sequence can never be generated. For example, a sequence of length 2080 is the largest that can fit within the period of the Mersenne Twister random number generator.

Deprecated since version 3.9, will be removed in version 3.11: The optional parameter *random*.
slate swan
peak loom
silver magnet
# slate swan ```await mes.add_reaction(":heavy_check_mark:")```
async def poll(ctx, *, message=None):
    if ctx.message.channel.name == "mod-chat":
        if message is None:
            await ctx.send("Argument error")
        await ctx.message.delete()
        await ctx.send(f"<@&role-id>, `{message}`")
        await mes.add_reaction(":thumbsup:")
        await mes.add_reaction(":thumbsdown:")
    else:
        return```
is this good?
wicked atlas
silver magnet
#

its a variable?

slate swan
#
@client.command()
@commands.has_permissions(manage_messages=True)
async def welcome(ctx):
    guild = ctx.guild
    voice_client: discord.VoiceClient = discord.utils.get(client.voice_clients, guild = guild)
    while True:
      audio_source_list = [discord.FFmpegPCMAudio('file.mp3'), discord.FFmpegPCMAudio('clip2.mp3'), discord.FFmpegPCMAudio('clip3.mp3'),         discord.FFmpegPCMAudio('clip5.mp3'), discord.FFmpegPCMAudio('clip6.mp3'), discord.FFmpegPCMAudio('clip7.mp3'), discord.FFmpegPCMAudio('clip9.mp3')]
      audio_source = audio_source_list[:]
      random.shuffle(audio_source)
      for i in range(7):
         if voice_client.is_playing():
            continue
         else:
            voice_client.play(audio_source.pop(), after = None)
            await asyncio.sleep(120)
#

@wicked atlas ?

wicked atlas
#

random.shuffle just returns the list, but with it's contents in a random order. That wouldn't work because it's a list

slate swan
#

oo

#

use .pop()?

slate swan
silver magnet
slate swan
wicked atlas
wicked atlas
#

Yeah, I would suggest you use the after kwarg, because otherwise there's going to be a lot of unnecessary looping in the background

slate swan
potent spear
silver magnet
#

@wicked atlas I tried and it really only duplicated the message. I don't know where to place it.

slate swan
#
@client.command()
async def poll(ctx, *, message=None):
    if ctx.message.channel.name == "mod-chat":
        if message is None:
            mes = await ctx.send("Argument error")
            return
        await ctx.message.delete()
        mes = await ctx.send(f"<@&role-id>, `{message}`")
        await mes.add_reaction(":thumbsup:")
        await mes.add_reaction(":thumbsdown:")
    else:
        return
#

Try this @silver magnet

silver magnet
#

hm

wicked atlas
#

I mean, that wouldn't get you the message object

slate swan
#

wait acually

wicked atlas
#
@client.command()
async def poll(ctx, *, message=None):
    if ctx.message.channel.name == "mod-chat":
        if message is None:
            await ctx.send("Argument error")
            return
        await ctx.message.delete()
        mes = await ctx.send(f"<@&role-id>, `{message}`")
        await mes.add_reaction(":thumbsup:")
        await mes.add_reaction(":thumbsdown:")
    else:
        return
slate swan
#

yep just changed it didnt see

slate swan
slate swan
potent spear
silver magnet
wicked atlas
# slate swan True, how would we go on about this?
AUDIO_SOURCE_LIST = [...]

def play_audio(voice_client, sources):
    try:
        source = next(sources)
    except StopIteration:
        random.shuffle(AUDIO_SOURCE_LIST)
        sources = iter(AUDIO_SOURCE_LIST)

    voice_client.play(source, after=play_audio(voice_client, sources))

play_audio(voice_client, iter(AUDIO_SOURCE_LIST))
```I might do something like this
#

there's probrably a better way to do it

slate swan
slate swan
#

I want it to indefinitely play the clips.

silver magnet
wicked atlas
slate swan
wicked atlas
#

It would iterate through the sources iterable until it reaches the end, then it shuffles it and starts again

silver magnet
slate swan
silver magnet
#

i am trying to make a trigger, how do i? i tried this but i am still very new to python

async def triggers(ctx):
    if ctx.message.user == "hello":
        await ctx.send("hi")```
#

something must be horribly wrong

slate swan
# wicked atlas It would iterate through the `sources` iterable until it reaches the end, then i...
@client.command()
@commands.has_permissions(manage_messages=True)
async def welcome(ctx):
    guild = ctx.guild
    voice_client: discord.VoiceClient = discord.utils.get(client.voice_clients, guild = guild)

    while True:
        audio_source_list = [discord.FFmpegPCMAudio('file.mp3'), discord.FFmpegPCMAudio('clip2.mp3'), discord.FFmpegPCMAudio('clip3.mp3'), discord.FFmpegPCMAudio('clip5.mp3'), discord.FFmpegPCMAudio('clip6.mp3'), discord.FFmpegPCMAudio('clip7.mp3'), discord.FFmpegPCMAudio('clip9.mp3')]

        def play_audio(voice_client, sources):
            try:
                source = next(sources)
            except StopIteration:
                random.shuffle(audio_source_list)
                sources = iter(audio_source_list)

            voice_client.play(source, after=play_audio(voice_client, sources))

        play_audio(voice_client, iter(audio_source_list))
wicked atlas
slate swan
boreal ravine
wicked atlas
wicked atlas
slate swan
#

Once the audio ends: We get:

TypeError: <lambda>() takes 0 positional arguments but 1 was given
slate swan
wicked atlas
#

the lambda error you can do this, i just read the docs again

lambda e: play_audio(voice_client, sources) 
#

it passes an error as a paremeter

boreal ravine
wicked atlas
#

well, for events outside of discord's events

silver magnet
#

i still need to take more tutorials but its literally midnight over here

wicked atlas
#

remove that loop

slate swan
slate swan
boreal ravine
slate swan
#

Bc the clips play back to back, I want to timeout for 30 seconds

wicked atlas
wicked atlas
#

but that would prevent it from playing it for 30 secs the first time

boreal ravine
heavy folio
slate swan
slate swan
heavy folio
#

you dont give them the code

slate swan
#

Understandable, My fault

heavy folio
#

and because hes a beginner he should be taught some good practices

#

e.g. using error handlers instead of making args None, etc

slate swan
#

if your gonna make an example make it the best you can tbh

worthy wagon
#

didn't know they added something called messag

slate swan
#

it detects messag lemon_pika

true moon
#

I have problem

#

when i use on_message event no command works why

#

even the program has no errors

heavy folio
#

@true moon dont use on_message

#

If you need commands, use the commands extension. Docs: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html Why should I use the commands extension? - Prevents spaghetti code - Better performance - Easy handling and processing of command arguments - Argument type converters - Easy sub commands - Command cooldowns - Built-in help function - Easy prefix management - Command checks, for controlling when they're to be invoked - Ability to add command modules via extensions/cogs - Still able to do everything you can do with Client

torn sail
#

I think he means that his commands aren’t working cause his on_message event

slate swan
torn sail
slate swan
#

or you can just use .listen()