-3
from discord.ext import commands
import datetime
import time


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


@client.event
async def on_ready():
    print('Бот готов')


# выдача обычной роли
@client.event
async def on_member_join(member):
    standart_channel = client.get_channel(912753884068479029)
    standart_role = discord.utils.get(member.guild.roles, id=912793481162928208)

    await member.add_roles(standart_role)
#######################################################################


# !clear
@client.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def clear(ctx, amount=100):
    await ctx.channel.purge(limit=amount + 1)
#######################################################################


# !kick
@client.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def kick(ctx, member: discord.Member, *, reason=None):
    await member.kick(reason=reason)
    await ctx.send(f'кикнут грешник по имени {member.mention}')
#######################################################################


# !ban
@client.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def ban(ctx, member: discord.Member, *, reason=None):
    await member.ban(reason=reason)
    await ctx.send(
        f'Забанен грешник по имени {member.mention}. Он больше не будет мучать наш сервер своими грязными делишками как минимум 7 дней')
#######################################################################


time_window_milliseconds = 5000
max_msg_per_window = 5
author_msg_times = {}
# Struct:
# {
#    "<author_id>": ["<msg_time", "<msg_time>", ...],
#    "<author_id>": ["<msg_time"],
# }

@client.event
async def on_message(ctx):
    global author_msg_counts

    author_id = ctx.author.id
    curr_time = datetime.datetime.now().timestamp() * 1000

    if not author_msg_times.get(author_id, False):
        author_msg_times[author_id] = []

    author_msg_times[author_id].append(curr_time)

    expr_time = curr_time - time_window_milliseconds

    expired_msgs = [
        msg_time for msg_time in author_msg_times[author_id]
        if msg_time < expr_time
    ]

    for msg_time in expired_msgs:
        author_msg_times[author_id].remove(msg_time)


    if len(author_msg_times[author_id]) > max_msg_per_window:
        await ctx.send('Не спамь')


token = 'ты не спишешь мой токен'

client.run(token)```
6
  • В чём суть вопроса? Кому и почему что-то не нравитЬся?
    – andreymal
    26 ноя 2021 в 15:36
  • Когда бот должен написать "Не спамь" вылазит ошибка в ctx.send('Не спамь')
    – user472298
    26 ноя 2021 в 16:53
  • Какая ошибка ?.
    – andreymal
    26 ноя 2021 в 16:53
  • Ignoring exception in on_message Traceback (most recent call last): File "C:\Users\user\PycharmProjects\Дискорд боты\Перепись бота\venv\lib\site-packages\discord\client.py", line 343, in _run_event await coro(*args, **kwargs) File "C:\Users\user\PycharmProjects\Дискорд боты\Перепись бота\main.py", line 85, in on_message await ctx.send.message('Не спамь') AttributeError: 'Message' object has no attribute 'send'
    – user472298
    26 ноя 2021 в 16:56
  • 1
    А, ну вы зачем-то внутри функции on_message объект message обозвали объектом ctx. Замените ctx на message и отправляйте сообщения через await message.channel.send(...) как описано в примерах к документации discordpy.readthedocs.io/en/stable/…
    – andreymal
    26 ноя 2021 в 17:01

2 ответа 2

2

Ну смотрите, вы зачем-то внутри функции on_message объект message обозвали объектом ctx. Замените ctx на message и отправляйте сообщения в канал, от куда поступил запрос, то есть через await message.channel.send(...)

1

В ивент on_message передаётся message
Из docs видим, чтобы вывести сообщение, нужно написать message.channel.send

@client.event
async def on_message(message):
    global author_msg_counts

    author_id = message.author.id
    curr_time = datetime.datetime.now().timestamp() * 1000

    if not author_msg_times.get(author_id, False):
        author_msg_times[author_id] = []

    author_msg_times[author_id].append(curr_time)

    expr_time = curr_time - time_window_milliseconds

    expired_msgs = [
        msg_time for msg_time in author_msg_times[author_id]
        if msg_time < expr_time
    ]

    for msg_time in expired_msgs:
        author_msg_times[author_id].remove(msg_time)


    if len(author_msg_times[author_id]) > max_msg_per_window:
        await message.channel.send('Не спамь')

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.