Skip to content

Commit 84934e4

Browse files
committed
PEP8 + Firebase update
1 parent 2f7c6d9 commit 84934e4

24 files changed

+473
-316
lines changed

.env_template

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
TOKEN=
22
APPLICATIONID=
3-
MONGODB=
43
FORTNITEAPI=
54
XBOXAPI=
65
DEBUGMODE=OFF

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
__pycache__
2-
gears/__pycache__
2+
**/__pycache__
33
bin/*
44
*.exe
55
.env

README.md

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,30 @@
1-
# R4Bot ![Version](https://img.shields.io/badge/Latest-1.0.1/master-blue.svg)
1+
# R4Bot ![Version](https://img.shields.io/badge/Latest-1.1/master-blue.svg)
22
Discord-бот, созданный для облегчения модерации серверов, и не только. Используются слэш-команды.
33

44
## 🛠️ Установка
55
1. Клонируйте репозиторий:
6-
```BASH
7-
git clone https://github.com/Rarmash/R4bot.git
8-
```
6+
```BASH
7+
git clone https://github.com/Rarmash/R4bot.git
8+
```
99
2. Смените директорию:
10-
```BASH
11-
cd R4bot
12-
```
10+
```BASH
11+
cd R4bot
12+
```
1313
3. Установите зависимости:
14-
```BASH
15-
pip install -r requirements.txt
16-
```
14+
```BASH
15+
pip install -r requirements.txt
16+
```
1717
4. Загрузите и установите [FFMPEG](https://ffmpeg.org/) (как вариант - в корень проекта).
1818

1919
5. Запустите файл Python:
20-
```BASH
21-
python main.py
22-
```
20+
```BASH
21+
python main.py
22+
```
2323

2424
6. Настройте бота через файлы servers.json и .env (шаблон - [.env_template](https://github.com/Rarmash/R4Bot/blob/master/.env_template)).
2525

26+
7. Сгенерируйте ключ доступа к своему приложению [Firebase](https://console.firebase.google.com) (в панели управления: `Project Settings` -> `Service accounts` -> `Firebase Admin SDK` -> `Python`).
27+
2628
## 🛠️ О servers.json:
2729
Бот поддерживает нахождение на нескольких серверах. Просто продублируйте блок с настройками сервера и заполните его.
2830
```JSON
@@ -56,7 +58,6 @@ python main.py
5658
```ENV
5759
TOKEN= // Токен бота Discord
5860
APPLICATIONID= // Application ID приложения бота с Discord Developer Portal
59-
MONGODB= // Адрес для подключения к БД MongoDB
6061
FORTNITEAPI= // Ключ API для получения данных с https://fortnite-api.com/
6162
XBOXAPI= // Ключ API для получения данных с https://xbl.io/
6263
DEBUGMODE=OFF // Значение DEBUG-режима

gears/events.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
from discord.ext import commands
22

3+
34
class Events(commands.Cog):
45

56
def __init__(self, bot):
67
self.bot = bot
7-
8+
89
@commands.Cog.listener()
910
async def on_application_command_error(self, ctx, error):
1011
if isinstance(error, commands.CommandOnCooldown):
@@ -16,12 +17,13 @@ async def on_voice_state_update(self, member, before, after):
1617
# Check if the member's voice state has changed and if they were in a voice channel before the update
1718
voice_state = member.guild.voice_client
1819
if voice_state is None:
19-
return
20+
return
2021

21-
# Check if the voice channel is empty (only the bot remains in the channel)
22+
# Check if the voice channel is empty (only the bot remains in the channel)
2223
if len(voice_state.channel.members) == 1:
2324
# If the voice channel is empty, disconnect the bot from the voice channel
2425
await voice_state.disconnect()
25-
26+
27+
2628
def setup(bot):
27-
bot.add_cog(Events(bot))
29+
bot.add_cog(Events(bot))

gears/fortnite.py

Lines changed: 58 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,30 @@
11
import discord
2-
from discord.ext import commands
3-
from discord.commands import SlashCommandGroup
4-
from options import fortniteapi, myclient, servers_data
52
import requests
3+
from discord.commands import SlashCommandGroup
4+
from discord.ext import commands
5+
6+
from modules.firebase import update_record, get_from_record, search_record_id
7+
from options import fortniteapi, servers_data
8+
9+
10+
# Helper function to make a request to the Fortnite API
11+
def fortnite_api_request(username):
12+
request_url = f"https://fortnite-api.com/v2/stats/br/v2?name={username}"
13+
response = requests.get(request_url, params={"displayName": username}, headers={"Authorization": fortniteapi})
14+
response_data = response.json()
15+
return response_data.get("data"), response_data.get("status")
16+
17+
18+
# Helper function to get the Fortnite username for the user
19+
def get_fortnite_username(ctx, username):
20+
if not username:
21+
author_id = str(ctx.author.id)
22+
user_data = get_from_record(str(ctx.guild.id), "Users", author_id)
23+
if user_data:
24+
username = user_data.get("fortnite")
25+
26+
return username
27+
628

729
class Fortnite(commands.Cog):
830
def __init__(self, bot, servers_data):
@@ -11,47 +33,33 @@ def __init__(self, bot, servers_data):
1133

1234
fortnite = SlashCommandGroup("fortnite", "Команды по Fortnite")
1335

14-
# Helper function to make a request to the Fortnite API
15-
def fortnite_api_request(self, username):
16-
request_url = f"https://fortnite-api.com/v2/stats/br/v2?name={username}"
17-
response = requests.get(request_url, params={"displayName": username}, headers={"Authorization": fortniteapi})
18-
response_data = response.json()
19-
return response_data.get("data"), response_data.get("status")
20-
21-
# Helper function to get the Fortnite username for the user
22-
def get_fortnite_username(self, ctx, username):
23-
if not username:
24-
author_id = str(ctx.author.id)
25-
user_data = myclient[f"{str(ctx.guild.id)}"]["Users"].find_one({"_id": author_id})
26-
if user_data:
27-
username = user_data.get("fortnite")
28-
29-
return username
30-
3136
# Command to view Fortnite stats for a player
3237
@fortnite.command(description='Посмотреть статистику по игроку')
33-
async def stats(self, ctx: discord.ApplicationContext, username = None):
34-
Collection = myclient[f"{str(ctx.guild.id)}"]["Users"]
38+
async def stats(self, ctx: discord.ApplicationContext, username=None):
3539
server_data = self.servers_data.get(str(ctx.guild.id))
3640
if not server_data:
3741
return
38-
42+
3943
await ctx.defer()
40-
44+
4145
# Get the Fortnite username for the player
4246
username = self.get_fortnite_username(ctx, username)
4347
# Check if the Fortnite username is available
4448
if not username:
45-
await ctx.respond("Вы не привязали профиль Fortnite к учётной записи Discord. Сделайте это, используя команду `/fortnite connect <username>`!")
49+
await ctx.respond(
50+
"Вы не привязали профиль Fortnite к учётной записи Discord. Сделайте это, используя команду "
51+
"`/fortnite connect <username>`!")
4652
return
47-
53+
4854
# Make a request to the Fortnite API for the stats data
4955
stats_data, status = self.fortnite_api_request(username)
50-
56+
5157
# Handle different status codes
5258
if status == 403:
5359
guide_files = [discord.File(f'resources/fortnite/fortnitestatsguide{i}.png') for i in range(1, 4)]
54-
await ctx.respond(f"❗ Данные игрока **{username}** скрыты (ошибка **{status}**).\nЕсли это ваш аккаунт, откройте статистику в настройках игры.", files=guide_files)
60+
await ctx.respond(
61+
f"❗ Данные игрока **{username}** скрыты (ошибка **{status}**).\nЕсли это ваш аккаунт, откройте статистику в настройках игры.",
62+
files=guide_files)
5563
return
5664
elif status == 404:
5765
await ctx.respond(f"❗ Игрок **{username}** не найден (ошибка **{status}**).")
@@ -61,7 +69,8 @@ async def stats(self, ctx: discord.ApplicationContext, username = None):
6169
return
6270
try:
6371
# Create and send the stats embed
64-
embed = discord.Embed(title=f'Статистика игрока {stats_data["account"]["name"]}', color=int(server_data.get("accent_color"), 16))
72+
embed = discord.Embed(title=f'Статистика игрока {stats_data["account"]["name"]}',
73+
color=int(server_data.get("accent_color"), 16))
6574
embed.add_field(name="🎟️ Уровень боевого пропуска", value=f'{stats_data["battlePass"]["level"]}')
6675
embed.add_field(name="🎮 Всего матчей сыграно", value=f'{stats_data["stats"]["all"]["overall"]["matches"]}')
6776
embed.add_field(name="👑 Всего побед", value=f'{stats_data["stats"]["all"]["overall"]["wins"]}')
@@ -71,22 +80,26 @@ async def stats(self, ctx: discord.ApplicationContext, username = None):
7180
embed.add_field(name="🎖 Всего топ-25", value=f'{stats_data["stats"]["all"]["overall"]["top25"]}')
7281
embed.add_field(name="💀 Всего убийств", value=f'{stats_data["stats"]["all"]["overall"]["kills"]}')
7382
embed.add_field(name="☠️ Убийств в минуту", value=f'{stats_data["stats"]["all"]["overall"]["killsPerMin"]}')
74-
embed.add_field(name="☠️ Убийств за матч", value=f'{stats_data["stats"]["all"]["overall"]["killsPerMatch"]}')
83+
embed.add_field(name="☠️ Убийств за матч",
84+
value=f'{stats_data["stats"]["all"]["overall"]["killsPerMatch"]}')
7585
embed.add_field(name="⚰️ Всего смертей", value=f'{stats_data["stats"]["all"]["overall"]["deaths"]}')
7686
embed.add_field(name="📈 Общее K/D", value=f'{stats_data["stats"]["all"]["overall"]["kd"]}')
7787
embed.add_field(name="📉 % побед", value=f'{stats_data["stats"]["all"]["overall"]["winRate"]}')
78-
embed.add_field(name="🕓 Всего сыграно минут", value=f'{stats_data["stats"]["all"]["overall"]["minutesPlayed"]}')
79-
embed.add_field(name="🙋‍♂️ Всего игроков пережито", value=f'{stats_data["stats"]["all"]["overall"]["playersOutlived"]}')
80-
88+
embed.add_field(name="🕓 Всего сыграно минут",
89+
value=f'{stats_data["stats"]["all"]["overall"]["minutesPlayed"]}')
90+
embed.add_field(name="🙋‍♂️ Всего игроков пережито",
91+
value=f'{stats_data["stats"]["all"]["overall"]["playersOutlived"]}')
92+
8193
# Add the owner of the profile if available in the database
8294
try:
83-
embed.add_field(name = "Владелец профиля", value=f"<@{Collection.find_one({'fortnite': username})['_id']}>")
95+
embed.add_field(name="Владелец профиля",
96+
value=f"<@{search_record_id(str(ctx.guild.id), "Users", "fortnite", username)}>")
8497
except TypeError:
8598
pass
86-
await ctx.respond(embed = embed)
99+
await ctx.respond(embed=embed)
87100
except KeyError:
88101
await ctx.respond("Ошибка при получении статистики.")
89-
102+
90103
# Command to view the Fortnite map
91104
@fortnite.command(description='Посмотреть карту')
92105
async def map(self, ctx: discord.ApplicationContext):
@@ -104,15 +117,14 @@ async def map(self, ctx: discord.ApplicationContext):
104117

105118
embed = discord.Embed(title='Карта Fortnite', color=int(server_data.get("accent_color"), 16))
106119
embed.set_image(url=map_data)
107-
await ctx.respond(embed=embed)
108-
120+
await ctx.respond(embed=embed)
121+
109122
@fortnite.command(description='Привязать профиль Fortnite к учётной записи Discord')
110123
async def connect(self, ctx: discord.ApplicationContext, username):
111124
server_data = self.servers_data.get(str(ctx.guild.id))
112125
if not server_data:
113126
return
114127

115-
Collection = myclient[f"{str(ctx.guild.id)}"]["Users"]
116128
await ctx.defer()
117129
author_id = str(ctx.author.id)
118130

@@ -121,9 +133,12 @@ async def connect(self, ctx: discord.ApplicationContext, username):
121133
await ctx.respond(f"При добавлении возникла ошибка **{status}**.\nВозможно, вы неверно указали никнейм.")
122134
return
123135

124-
Collection.update_one({"_id": author_id}, {"$set": {"fortnite": username}})
125-
embed = discord.Embed(description=f"Аккаунт {username} был успешно привязан к вашей учётной записи!\nЕсли вы измените никнейм в игре, не забудьте его перепривязать здесь.", color=int(server_data.get("accent_color"), 16))
136+
update_record(str(ctx.guild.id), "Users", author_id, {"fortnite": username})
137+
embed = discord.Embed(
138+
description=f"Аккаунт {username} был успешно привязан к вашей учётной записи!\nЕсли вы измените никнейм в игре, не забудьте его перепривязать здесь.",
139+
color=int(server_data.get("accent_color"), 16))
126140
await ctx.respond(embed=embed)
127-
141+
142+
128143
def setup(bot):
129-
bot.add_cog(Fortnite(bot, servers_data))
144+
bot.add_cog(Fortnite(bot, servers_data))

0 commit comments

Comments
 (0)