Python discord client event

Quickstart¶

This page gives a brief introduction to the library. It assumes you have the library installed, if you don’t check the Installing portion.

A Minimal Bot¶

Let’s make a bot that responds to a specific message and walk you through it.

It looks something like this:

# This example requires the 'message_content' intent. import discord intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents=intents) @client.event async def on_ready(): print(f'We have logged in as client.user>') @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('$hello'): await message.channel.send('Hello!') client.run('your token here') 

Let’s name this file example_bot.py . Make sure not to name it discord.py as that’ll conflict with the library.

There’s a lot going on here, so let’s walk you through it step by step.

  1. The first line just imports the library, if this raises a ModuleNotFoundError or ImportError then head on over to Installing section to properly install.
  2. Next, we create an instance of a Client . This client is our connection to Discord.
  3. We then use the Client.event() decorator to register an event. This library has many events. Since this library is asynchronous, we do things in a “callback” style manner. A callback is essentially a function that is called when something happens. In our case, the on_ready() event is called when the bot has finished logging in and setting things up and the on_message() event is called when the bot has received a message.
  4. Since the on_message() event triggers for every message received, we have to make sure that we ignore messages from ourselves. We do this by checking if the Message.author is the same as the Client.user .
  5. Afterwards, we check if the Message.content starts with ‘$hello’ . If it does, then we send a message in the channel it was used in with ‘Hello!’ . This is a basic way of handling commands, which can be later automated with the discord.ext.commands – Bot commands framework framework.
  6. Finally, we run the bot with our login token. If you need help getting your token or creating a bot, look in the Creating a Bot Account section.

Now that we’ve made a bot, we have to run the bot. Luckily, this is simple since this is just a Python script, we can run it directly.

Now you can try playing around with your basic bot.

© Copyright 2015-present, Rapptz. Created using Sphinx 4.4.0.

Источник

adamsbytes / python-discord-events.md

As of writing this, documentation for the Discord events API is a little lacking and the feature is not yet integrated into Discord.py.

This gist presents a basic class that performs a couple event actions against the Discord API.

To interact with the Discord API you need an async http client, for this gist it’ll be aiohttp . You’ll need a Discord bot created, and to have a token generated for that bot. Your bot will also need event permissions in the guilds/servers you are trying to create events in.

For information on the return content of the list_guild_events() function, see this section of Discord’s API docs.

Remember, these functions are asynchronous! They’ll need to be awaited, not just called like normal functions. If you’re new to that sort of thing, see this guide for details.

import json import aiohttp class DiscordEvents: '''Class to create and list Discord events utilizing their API''' def __init__(self, discord_token: str) -> None: self.base_api_url = 'https://discord.com/api/v8' self.auth_headers = < 'Authorization':f'Bot discord_token>', 'User-Agent':'DiscordBot (https://your.bot/url) Python/3.9 aiohttp/3.8.1', 'Content-Type':'application/json' > async def list_guild_events(self, guild_id: str) -> list: '''Returns a list of upcoming events for the supplied guild ID Format of return is a list of one dictionary per event containing information.''' event_retrieve_url = f'self.base_api_url>/guilds/guild_id>/scheduled-events' async with aiohttp.ClientSession(headers=self.auth_headers) as session: try: async with session.get(event_retrieve_url) as response: response.raise_for_status() assert response.status == 200 response_list = json.loads(await response.read()) except Exception as e: print(f'EXCEPTION: e>') finally: await session.close() return response_list async def create_guild_event( self, guild_id: str, event_name: str, event_description: str, event_start_time: str, event_end_time: str, event_metadata: dict, event_privacy_level=2, channel_id=None ) -> None: '''Creates a guild event using the supplied arguments The expected event_metadata format is event_metadata= The required time format is %Y-%m-%dT%H:%M:%S''' event_create_url = f'self.base_api_url>/guilds/guild_id>/scheduled-events' event_data = json.dumps(< 'name': event_name, 'privacy_level': event_privacy_level, 'scheduled_start_time': event_start_time, 'scheduled_end_time': event_end_time, 'description': event_description, 'channel_id': channel_id, 'entity_metadata': event_metadata, 'entity_type': 3 >) async with aiohttp.ClientSession(headers=self.auth_headers) as session: try: async with session.post(event_create_url, data=event_data) as response: response.raise_for_status() assert response.status == 200 except Exception as e: print(f'EXCEPTION: e>') finally: await session.close()

Источник

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!

Источник

Читайте также:  Radio buttons grouping in html
Оцените статью