mistertwst
mistertwst

Reputation: 75

Commands with arguments using Discord.py

import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
import random
from PIL import Image

Client = discord.Client()
client = commands.Bot(command_prefix = "-")`
@client.command
async def spam(ctx, arg):
    count = 0 
    await Context.send(message.channel, "Wait for it....")
    time.sleep(3)
    while count < 20:
        await ctx.send(arg)
        time.sleep(3)
        count = count + 1

This code is supposed to mention the person specified in the argument. For example if someone typed -spam @Bob the bot should say

@Bob
@Bob 20 times

Upvotes: 2

Views: 10614

Answers (2)

Some Things
Some Things

Reputation: 81

To start, you don't need both discord.Client() and commands.Bot()

Here is a breakdown:

import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
import random
from PIL import Image

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

@client.command()
async def spam(ctx, user:discord.Member): #Replace arg with user:discord.Member, discord.Member has many attributes that allow you to do multiple actions
    count = 0 
    await ctx.send(message.channel, "Wait for it....") #replace Context with ctx, ctx is the Context
    time.sleep(3)
    while count <= 20: # Replaced count<20 with count<=20 otherwise it'll only spam 19 times 
        await ctx.send(user.mention) #changed args to user.mention, user.mention mentions the user
        time.sleep(3)
        count = count + 1

Upvotes: 0

Patrick Haugh
Patrick Haugh

Reputation: 60944

There's no need to instantiate both discord.Client and commands.Bot. Bot is a subclass of Client.

Bot.command is a function that returns a decorator, not itself a decorator. You need to call it to use it to decorate a coroutine:

@client.command()

You should probably be using a converter to acquire the user you're pinging.

Context is the class that ctx is an instance of. You should be accessing all of the methods through ctx.

Don't use time.sleep, as it blocks the event loop. Await asyncio.sleep instead.

from discord.ext.commands import Bot
from asyncio import sleep
from discord import User

client = Bot(command_prefix = "-")

@client.command()
async def spam(ctx, user: User):
    await ctx.send("Wait for it....")
    await sleep(3)
    for _ in range(20):
        await ctx.send(user.mention)
        await sleep(3)

client.run("token")

Upvotes: 1

Related Questions