Статистика дискорд бот python

недавно начал изучать библиотеку pil для discord.py. хочу сделать бота, что будет менять баннер сервера и обновлять статистику каждые 10-15 секунд. писал код да бы понять ,как работает библиотека, но сегодня узнал про метод tasks.loop() и решил попробовать воспользоваться им, но очень много ошибок. переменные не работают. буду благодарен любой помощи!

import discord from discord.ext import commands , tasks from discord.utils import get from PIL import Image, ImageDraw, ImageFont, ImageOps import asyncio import os from time import sleep import requests import io import datetime bot = commands.Bot( command_prefix = '.', intents = discord.Intents.all(), ) token = 'токен стёртый!' @bot.event async def on_ready(): print(f'бот активирован!') print(f'название бота: ') print(f'айди бота: ') print(f'токен: ') print(f'') await bot.change_presence(status = discord.Status.online, activity = discord.Game('morwaezz | dc: morwaezz#5269')) banner.start() @tasks.loop(seconds = 10) async def banner(ctx): guild = bot.get_guild(1071401936676470864) members = guild.members voice_channels = [member for member in members if member.voice and member.voice.channel] with Image.open('bot morwaezz/banners/banner.png') as image: # Создание объекта ImageDraw для рисования на изображении draw = ImageDraw.Draw(image) # получаем время, которое было 2 часа назад two_hours_ago = datetime.datetime.utcnow() - datetime.timedelta(hours = 2) # создаем словарь для хранения количества сообщений каждого участника message_count = <> # перебираем все текстовые каналы на сервере for channel in ctx.guild.text_channels: # перебираем все сообщения в канале, опубликованные за последние 2 часа async for message in channel.history(after=two_hours_ago): # проверяем, что сообщение было отправлено участником сервера if message.author in members: # увеличиваем количество сообщений для данного участника if message.author in message_count: message_count[message.author] += 1 else: message_count[message.author] = 1 most_active_member = max(message_count, key=message_count.get) activity = most_active_member.activity font = ImageFont.truetype('bot morwaezz/banners/ofont.ru_Montserrat.ttf', size = 59) draw.text((1077, 555), f' ', fill='white', font=font) bot.guild = bot.get_guild(id) voice_users = sum(len(vc.members) for vc in bot.guild.voice_channels) font = ImageFont.truetype('bot morwaezz/banners/ofont.ru_Montserrat.ttf', size = 88) draw.text((1603, 872), f'', fill = 'white', font=font) font = ImageFont.truetype('bot morwaezz/banners/ofont.ru_Montserrat.ttf', size = 60) draw.text((627, 776), f''[:20], fill='gray', font=font) if isinstance(most_active_member, discord.Member): font = ImageFont.truetype('bot morwaezz/banners/ofont.ru_Montserrat.ttf', size = 100) draw.text((627, 662), f''[:8], fill='white', font=font) else: font = ImageFont.truetype('bot morwaezz/banners/ofont.ru_Montserrat.ttf', size = 100) draw.text((627, 662), f''[:8], fill='white', font=font) url = str(most_active_member.avatar.url)[:-10] response = requests.get(url, stream=True) response = Image.open(io.BytesIO(response.content)) response = response.convert('RGBA') # Обрезка изображения до круга response = ImageOps.fit(response, (315, 315), method=Image.LANCZOS, centering=(0.5, 0.5)) mask = Image.new('L', (315, 315), 0) draw = ImageDraw.Draw(mask) draw.ellipse((0, 0, 315, 315), fill=255) response.putalpha(mask) # Вставка изображения image.paste(response, (222, 601), response) image.save('bot morwaezz/banners/stats_banner.png') await guild.edit(file=discord.File('bot morwaezz/banners/stats_banner.png')) @bot.command() async def ask_question(ctx): await ctx.send("Какой ваш любимый цвет?") def check(message): return message.author == ctx.author and message.channel == ctx.channel response = await bot.wait_for('message', check=check) await ctx.send(f"Ваш любимый цвет - !") @bot.slash_command(description="Test command") async def test(interaction: discord.Interaction): await interaction.response.defer(ephemeral = True) await asyncio.sleep(10) await interaction.followup.send("My actual content") bot.run(token) 
Unhandled exception in internal background task 'banner'. Traceback (most recent call last): File "C:\Users\morwaezz\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\tasks\__init__.py", line 169, in _loop await self.coro(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: banner() missing 1 required positional argument: 'ctx' 

Источник

Читайте также:  Передача массива методу php

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 User Stats Bot with Python and MySQL

teraprath/discord-stats-bot

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 Bot with an User Stats System (Level, EXP and Ranks) using the discord.py libary and a MySQL-Databse. It can be easily expanded with the Discord Stats Web Panel , which I also developed.

While this is easy to use, I recommend it as a base for a Discord Bot rather than a finished bot.

Image

  1. Download the source and upload it on your Linux Server.
  2. Then install the discord.py libary:
python3 -m pip install -U discord.py 

If you are using Windows, then the following should be used instead:

py -3 -m pip install -U discord.py 
  1. Set up your MySQL database and create a database.
  2. Go to the uploaded folder in config.py and enter your MySQL data.
# MySQL Database host = "localhost" # Or your host user = "root" # Or your username password = "password" # Or your password database = "dcstats" # Or your name # Discord token = ""
  1. It is also important that you provide a bot token. If you don’t know how to create a bot on Discord, this video might help you.
  2. Invite your discord bot on your server
  3. Paste the Bot Token in config.py and save it
  4. And now finally start the bot with the following commands (Linux):
cd /home/your-folder/ python3 bot.py

You can modify the bot as you want.

Читайте также:  Sorting set in python

Refine with Discord Stats Web

Download the Discord Stats Web for free and have a good visualization of the statistics with a ranking system.

Image

About

A simple Discord User Stats Bot with Python and MySQL

Источник

Discord.py server stats command

I want to make a command that will show most useful server stats. I tried to make something like this:

@bot.command() async def serverstats(ctx): embed=discord.Embed(title=f"Statystyki serwera ") embed.add_field(name="Users:", value=ctx.guild.members, inline=False) embed.add_field(name="Channels:", value=ctx.guild.channels, inline=False) embed.add_field(name="Messages sent:", value=. inline=False) await ctx.send(embed=embed) 

But i don’t know how can i make messages counter, and other counters return not correct or strange data

I would start with for channel in ctx.guild.channels: print(channel) . And next I would try to use object channels to count messages in this channel.

2 Answers 2

For the users and channel counter, you would use the len() function to count how many there are. If you don’t have the members intent enabled, you can also use ctx.guild.member_count .

# Using len(). embed.add_field(name="Users:", value=ctx.guild.member_count, inline=False) embed.add_field(name="Channels:", value=len(ctx.guild.channels), inline=False) 

For messages however, you will need to use a database or global variable and manually increase the entry each time a message is sent. A global variable is much simpler to use than a database, however it will be flushed whenever the script ends or is restarted.

On a side note, if you want to use a database anyway, I recommend you check out dataset.

# Using a global variable (dictionary) # Somewhere in your code. messagecounts = <> . @bot.event async def on_message(message): if message.guild.id not in messagecounts.keys(): # Make sure there's already an entry. If not, add one! messagecounts[message.guild.id] = 0 messagecounts[message.guild.id] += 1 # Sets the new count to 1 greater than the original. 

Then, to retrieve this amount, you would add the dictionary entry. Final Code:

# Somewhere above the command. messagecounts = <> @bot.command() async def serverstats(ctx): embed=discord.Embed(title=f"Statystyki serwera ") embed.add_field(name="Users:", value=ctx.guild.member_count, inline=False) embed.add_field(name="Channels:", value=len(ctx.guild.channels), inline=False) embed.add_field(name="Messages sent:", value=messagecounts[ctx.guild.id], inline=False) await ctx.send(embed=embed) @bot.event async def on_message(message): if message.guild.id not in messagecounts.keys(): messagecounts[message.guild.id] = 0 messagecounts[message.guild.id] += 1 

Источник

Читайте также:  Untitled Document

Table of Contents

dbots helps Discord bot developers group all your statistic posting needs into one poster, complete with seperate posting, and a loop to post to all services every n seconds.

Installing

Python 3.6 or higher is required! You can install dbots by running this command:

 python3 -m pip install -U dbots py -3 -m pip install -U dbots

To install package from the master branch, do the following:

git clone https://github.com/dbots-pkg/dbots.py  dbots.py python3 -m pip install -U

Examples

Example with client

Currently, only discord.py is supported as a usable client. (You can use any derivative of discord.py as long as it does not interfere with important properties used by dbots .)

Services

Supported Services

  • arcane-center.xyz (docs)
  • blist.xyz (docs)
  • botlist.space (docs)
  • botsdatabase.com (docs)
  • botsfordiscord.com (docs)
  • bots.ondiscord.xyz (docs)
  • carbonitex.net (docs)
  • dblista.pl (docs)
  • discordbots.co (docs)
  • discord.bots.gg (docs)
  • discordapps.dev (docs)
  • discord.boats (docs)
  • discordbotlist.com (docs)
  • discordbot.world (docs)
  • discordextremelist.xyz (docs)
  • bots.discordlabs.org (docs)
  • discordlistology.com (docs)
  • lbots.org (docs)
  • listmybots.com (docs)
  • mythicalbots.xyz (docs)
  • space-bot-list.xyz (docs)
  • topcord.xyz (docs)
  • top.gg (docs)
  • wonderbotlist.com (docs)
  • yabl.xyz (docs)

Adding Custom Services

You can add custom services by extending from the base service class ( dbots.Service ) and overriding the _post and aliases method.
Make sure to add the custom service class to the service keymap. ( dbots.Service.SERVICE_KEYMAP ) An example of adding a custom service can be shown here.

Adding a custom post function

You can add a custom post event by defining on_custom_post in the initialization of a Poster.
This function can be used when executing poster.post(‘custom’) and when all services are being posted to. An example of adding a custom post function can be shown here.

Contribution

Any contribution may be useful for the package! Make sure when making issues or PRs that the issue has not been addressed yet in a past issue/PR.

Источник

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