Herrmit Busen
Herrmit Busen

Reputation: 93

@client.command() in discord py is not working for me

I've got a problem with discord.py bot, client.event on_message commands work perfectly for me but client.command() doesnt work, I've tried reinstalling everything from python to anaconda but it still doesnt work. (and sorry if question and code was messy I'm sort of new to programming and stackoverflow)

code:

import discord
import random
import time
from discord.ext import commands
import discord.utils
songs = []
songs_string = """HaB
LionNorth
Stalingrad
"""
i2 = 0
for song_name in songs_string.splitlines():
    songs.insert(i2, song_name)
    i2 += 1

list1 = []

help = '''
все команды должны начинаться с точки 
dsw сюда ругательство,что бы добавить новое ругательство в sw на время сессии бота
time узнать текущее время
sabaton для получения случайной песни Сабатон (иногда может не работать из-за размера файла)
sw чтобы получить случайную ругань
'''

i = 0
string = f'''ПИДОРАС
ПОШЕЛ НАХУЙ
ДА ТЫ УЕБОК
не интересно,пидор
НАЧАЛЬНИК БЛЯТЬ,ЭТОТ ПИДОРАС ОБОСРАЛСЯ
бля ахуительная история
Я ТВОЙ НАЧАЛЬНИК
КТО БУДЕТ СОСАТЬ
ПОШЕЛ НА РАБОТУ
ЧИСТИ ГОВНО
НИХУЯ НЕ МОЖЕШЬ,ПОШЕЛ НАХУЙ
я с этим гондоном сидеть не буду бля
какие нахуй корабли?
'''
quotes_string = """Недостаточно овладеть премудростью, нужно также уметь пользоваться ею.
Тем, кто хочет учиться, часто вредит авторитет тех, кто учит.
Трудно быть хорошим..
"""
for word in string.splitlines():
    list1.insert(i, word)
    i += 1
restr = ["поговорим-по-душам", "🤓флудилка🤓", "⚠правила⚠", "🗯новости🗯"]
client = commands.Bot(command_prefix=".")


@client.command()
async def hi(ctx):
    await ctx.send('Hi!')

@client.event
async def on_member_join(member):
    for channel in member.guild.channels:
        if str(channel) == "welcome":
            await channel.send(f"""Welcome to the server {member.mention}""")
@client.event
async def on_message(message):
    if str(message.channel) not in restr:
            if message.content == ".sabaton":
                random.seed(time.time())
                randnum = random.randint(0, len(songs) - 1)
                await message.channel.send(file=discord.File(songs[randnum]))
            elif message.content == ".sw":
                random.seed(time.time())
                randnum = random.randint(0, len(list1) - 1)
                await message.channel.send(list1[randnum].upper())
            elif message.content == ".time":
                await message.channel.send(f"Current time is {time.localtime()}")
            elif message.content == ".help":
                await message.channel.send(help)
            if message.content.startswith(".dsw"):
                msg = message.content.split()
                output = ''
                for word in msg[1:]:
                    output += word
                    output += ' '
                await message.channel.send(f"{output} было добавлено в список ругательств на эту сессию")
                list1.append(output)`





client.run("token here")

Upvotes: 2

Views: 3389

Answers (1)

Diggy.
Diggy.

Reputation: 6944

When using an on_message event, you'll need the bot to process_commands() if you're planning on using command decorators:

@client.event
async def on_message(message):
    await client.process_commands(message)
    # rest of your on_message code

References:

  • on_message
  • Bot.process_commands() - "Without this coroutine, none of the commands will be triggered. If you choose to override the on_message() event, then you should invoke this coroutine as well."

Upvotes: 4

Related Questions