Discord bot python warn

Команда Discord Bot python 3.6 warn

Я работаю над модератором дискодорации бота. Сделал всю команду, кроме команды warn. Может ли кто-нибудь помочь мне сделать предупреждение команды.

Если член (с разрешением на управление членом) вводит ?warn @user reason бот сохранит предупреждение в файле.json.

И если пользователь говорит ?warnings @user бот покажет предупреждения пользователя.

1 ответ

Вы могли бы сделать что-то вроде этого

import discord from discord.ext.commands import commands,has_permissions, MissingPermissions import json with open('reports.json', encoding='utf-8') as f: try: report = json.load(f) except ValueError: report = <> report['users'] = [] client = discord.ext.commands.Bot(command_prefix = '?') @client.command(pass_context = True) @has_permissions(manage_roles=True, ban_members=True) async def warn(ctx,user:discord.User,*reason:str): if not reason: await client.say("Please provide a reason") return reason = ' '.join(reason) for current_user in report['users']: if current_user['name'] == user.name: current_user['reasons'].append(reason) break else: report['users'].append(< 'name':user.name, 'reasons': [reason,] >) with open('reports.json','w+') as f: json.dump(report,f) @client.command(pass_context = True) async def warnings(ctx,user:discord.User): for current_user in report['users']: if user.name == current_user['name']: await client.say(f" has been reported times : ") break else: await client.say(f" has never been reported") @warn.error async def kick_error(error, ctx): if isinstance(error, MissingPermissions): text = "Sorry <>, you do not have permissions to do that!".format(ctx.message.author) await client.send_message(ctx.message.channel, text) client.run("BOT_TOKEN") 

Где вы сохраняете все отчеты пользователя в файле с именем reports.json и вместо manage_roles=True, ban_members=True внутри @has_permissions Вы можете положить что-нибудь из документации

Читайте также:  Python wsgi http request

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A simple Discord warn bot, written in Discord.py

License

AtlasC0R3/warnbot-discordpy

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A simple Discord warn bot, written in Discord.py

NOTE: This is no longer supported, no more updates will be brought over to this. I have since made a full-fledged Discord.py bot, with a separate warn cog, and see no reason why I should carry over with this project.

Head over to releases, download the *.exe file and specify your user token, then you should be all right to go!

The Still Somewhat Easy Way (using Python directly)

Make sure Python is installed and that discord.py is installed through pip, then put your token inside data/token.txt and run warnbot.py! You should be good to go!

NOTE: If you want to use a user token (which I think is against the Discord ToS, but anyway), you will have to go inside warnbot.py and change the bot=True statement to bot=False

Edit warn command Warn command Remove warn command Warns command

EvieePy on GitHub Gist for providing a lot of amazing discord.py examples that I have used throughout this project

The Python Discord community for helping me out whenever I had problems with my Python scripts

The makers of Discord.py and Discord.ext for making this project possible

You for checking this out

About

A simple Discord warn bot, written in Discord.py

Источник

Events in discord.py 🐍

discord.py has an extensive collection of features. Events are one of the most useful of these. Events are used for welcoming bots, reaction roles, and lots of other functions. This guide will teach you more about events, and how you can use them in your discord bot. In the end, we will have the bot print to the console when it is signed in, and give it a simple moderation and logging system.

If you haven’t yet, I suggest reading the earlier post in this series, as this builds on the previous post.

import discord from discord.ext import commands bot = commands.Bot(command_prefix="!", case_insensitive=True) @bot.command(name='hello', description="Greet the user!") async def hello(ctx): await ctx.send(f"Hello ctx.author.name>!") # f-string bot.run('token') 

But what if we want to delete a message when a user sends a link in the chat? They obviously wouldn’t use a command. We can use the on_message event to trigger a function whenever a message is sent. We first want to use the event decorator to tell discord.py that this is an event.

@bot.event async def on_message(message): if 'https://' in message.content: await message.delete() await message.channel.send(f"message.author.mention> Don't send links!") else: await bot.process_commands(message) 

Automoderation 🔧

badwords = ['bad', 'words', 'here'] @bot.event async def on_message(message): for i in badwords: # Go through the list of bad words; if i in message: await message.delete() await message.channel.send(f"message.author.mention> Don't use that word here!") return # So that it doesn't try to delete the message again. await bot.process_commands(message) 

Logging 📜

Events are called by using the dispatch function. When a message is sent, the internals of discord.py uses bot.dispatch(‘message’, message_object) . This triggers other parts of discord.py to find the function called on_message and run it. So, we could make our own event that logs profanity! So let’s adapt on the code so that it will use a logging system!

badwords = ['bad', 'words', 'here'] @bot.event async def on_message(message): for i in badwords: # Go through the list of bad words; if i in message.content: await message.delete() await message.channel.send(f"message.author.mention> Don't use that word!") bot.dispatch('profanity', message, i) return # So that it doesn't try to delete the message again, which will cause an error. await bot.process_commands(message) 

Before beginning this section, you will need to know how to get channel IDs. You can follow this guide if you need to enable developer mode.

You will need to get your log channel ID so that the bot can access the specific channel. Don’t worry, IDs aren’t private, so you don’t have to worry about sharing them.

@bot.event async def on_profanity(message, word): channel = bot.get_channel(channel_id_here) # for me it's bot.get_channel(817421787289485322) embed = discord.Embed(title="Profanity Alert!",description=f"message.author.name> just said ||word>||", color=discord.Color.blurple()) # Let's make an embed! await channel.send(embed=embed) 
  • Created your own event
  • Created a simple automoderation system
  • Logged when the rules are broken
  • Created an embed

Next, we’ll be creating a Discord bot that moderates invite links!

Источник

Как сделать проверку варнов на боте?

Работаю над дискорд ботом, а именно над системой варнов(предупреждений).
Мне осталось лишь команда по проверке варнов.

Если у юзера не имеется один из варнов, то выдаёт эмбед и указывает его точное предупреждение (одно из трёх возможных), но вместе с этим ниже появляется эмбед о том, что варнов нет.

Если в ролях юзера (делаю всё именно через роли) нет варнов, то эмбед лишь один — отсутствие варнов.

Понимаю, что проблема именно с функцией об отсутствии варна, но как правильно написать уже ума не приложу.

@bot.command(aliases=['warns', 'wc']) async def warncheck(ctx, member: discord.Member): await ctx.message.delete() #Embeds nwemb=discord.Embed(timestamp=ctx.message.created_at, colour=discord.Color.from_rgb(47, 49, 54)) nwemb.set_author(name=member.name, icon_url=member.avatar_url ) nwemb.set_footer(text="<>".format(ctx.author.name), icon_url=ctx.author.avatar_url, ) nwemb.add_field(name='♢ Пользователь не имеет предупреждений.', value="Надеемся, что так будет и дальше") emb=discord.Embed(timestamp=ctx.message.created_at, colour=discord.Color.from_rgb(47, 49, 54)) emb.set_author(name=member.name, icon_url=member.avatar_url ) emb.set_footer(text="<>".format(ctx.author.name), icon_url=ctx.author.avatar_url, ) emb.add_field(name='♢ Пользователь имеет предупреждение #1.', value="Прочтите , чтобы не получить их ещё.") emb2=discord.Embed(timestamp=ctx.message.created_at, colour=discord.Color.from_rgb(47, 49, 54)) emb2.set_author(name=member.name, icon_url=member.avatar_url ) emb2.set_footer(text="<>".format(ctx.author.name), icon_url=ctx.author.avatar_url, ) emb2.add_field(name='♢ Пользователь имеет предупреждение #2.', value="Прочтите , чтобы не получить их ещё.") emb3=discord.Embed(timestamp=ctx.message.created_at, colour=discord.Color.from_rgb(47, 49, 54)) emb3.set_author(name=member.name, icon_url=member.avatar_url ) emb3.set_footer(text="<>".format(ctx.author.name), icon_url=ctx.author.avatar_url, ) emb3.add_field(name='♢ Пользователь имеет предупреждение #3.', value="Вы максимально приблизились к наказанию!") #Roles WarnR=["Warning I", "Warning II", "Warning III"] warn1r=ctx.guild.get_role(955753706673045524) warn2r=ctx.guild.get_role(955753778630524948) warn3r=ctx.guild.get_role(955753843910672404) #Action if warn1r in member.roles: await ctx.send(embed=emb) if warn2r in member.roles: await ctx.send(embed=emb2) if warn3r in member.roles: await ctx.send(embed=emb3) if WarnR not in member.roles: await ctx.send(embed=nwemb)

Источник

Оцените статью