-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
s1.py
325 lines (291 loc) · 13.7 KB
/
s1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#!/usr/bin/python
# -*- coding: utf-8 -*-
# web requests
import aiohttp
import discord
import urllib.parse
# default OS
import os
import asyncio
import sys
# image stuff
from PIL import Image, ImageFont, ImageDraw
# for docker image, use first value in "getenv" as key,
# if you want to run in python, use the empty field behind it to set the variable
# https://github.com/reactiflux/discord-irc/wiki/Creating-a-discord-bot-&-getting-a-token
BOT_TOKEN = os.getenv("token", "")
# name of the server it needs to search for
NAME = os.getenv("name", "")
# optional
# channel where it needs to post the message if almost empty etc.
MESSAGE_CHANNEL = int(os.getenv("channel", 0))
# amount of change needed to count
MIN_PLAYER_AMOUNT = int(os.getenv("minplayeramount", 20))
# amount of request to use for the calculation if the difference is more thatn min_player_amount
AMOUNT_OF_PREVIOUS_REQUESTS = int(os.getenv("prevrequestcount", 5))
# amount of players before it calls the server "started"
STARTED_AMOUNT = int(os.getenv("startedamount", 50))
# discord group id where is needs to post the message
GUILD = int(os.getenv("guild", 0))
# language for the mapname etc.
LANG = os.getenv("lang", "en-us")
# game to use for the bot: bf4/bf1 (bfv doesnt have favorites amount visable)
GAME = os.getenv("game", "bf1")
# choose image from the sample files, they will auto-update in code.
NO_BOTS = os.getenv("nobots", False)
# .png - image to show as avatar
AVATARIMAGE = os.getenv("avatarimage", "avatar_image")
# .png - image you want to show in message
MESSAGEIMAGE = os.getenv("infoimage", "info_image")
# fontfile used in the image
SMALLFONT = os.getenv("smallfont", "DejaVuSans.ttf")
BIGFONT = os.getenv("bigfont", "Catamaran-SemiBold.ttf")
"""BF1 version"""
# dont change
sinceEmpty = False
previousRequests = []
sincePlayerTrigger = AMOUNT_OF_PREVIOUS_REQUESTS
class LivePlayercountBot(discord.Client):
"""Discord bot to display the Battlefield tracker's true playercount in the bot status"""
async def on_ready(self):
print(f"Logged on as {self.user}\n" f"Started monitoring server {NAME}")
status = ""
picture = ""
async with aiohttp.ClientSession() as session:
while True:
try:
# change status
newstatus = await get_playercount(session)
if (
newstatus["serverInfo"] != status
): # avoid spam to the discord API
await self.change_presence(
activity=discord.Game(newstatus["serverInfo"])
)
status = newstatus["serverInfo"]
# send messages
try:
if MESSAGE_CHANNEL != 0:
global sinceEmpty
global sincePlayerTrigger # to not let it spam
test = False
for request in previousRequests:
if (
float(request) - float(newstatus["playerAmount"])
>= MIN_PLAYER_AMOUNT
and sincePlayerTrigger
> AMOUNT_OF_PREVIOUS_REQUESTS * 2
): # check last few requests for changes
await createMessage(
self,
MESSAGEIMAGE,
newstatus,
f"I'm low on players! Join me now!",
f"Perfect time to join without queue!\n{newstatus['serverInfo']}",
)
sincePlayerTrigger = 0
test = True
break
if not test: # if none worked
sincePlayerTrigger += 1
if newstatus["playerAmount"] <= 5: # counter since empty
sinceEmpty = True
if (
sinceEmpty == True
and newstatus["playerAmount"] >= STARTED_AMOUNT
): # run if 1 hour after starting and playercount is good
await createMessage(
self,
MESSAGEIMAGE,
newstatus,
f"I'm up and running!",
f"Feeling good :slight_smile:\n{newstatus['serverInfo']}",
)
sinceEmpty = False
if (
newstatus["playerAmount"] >= MIN_PLAYER_AMOUNT
and len(previousRequests) >= AMOUNT_OF_PREVIOUS_REQUESTS
): # if current is above or at 20 players and runs for at least a few mins
if all(
MIN_PLAYER_AMOUNT > request
for request in previousRequests
): # if the past messages are below 20
await createMessage(
self,
MESSAGEIMAGE,
newstatus,
f"Pre-round is over!",
f"No more waiting. If you join now you can instantly play.\n{newstatus['serverInfo']}",
)
if (
len(previousRequests) >= AMOUNT_OF_PREVIOUS_REQUESTS
): # if it has run more than 4 times
previousRequests.pop(0) # remove first item
previousRequests.append(
newstatus["playerAmount"]
) # add current in back
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(f"messageSend: {e} - line {exc_tb.tb_lineno} {fname}")
# change picture
if picture != newstatus["serverMap"]:
picture = newstatus["serverMap"]
with open(f"{AVATARIMAGE}.png", "rb") as f:
await self.user.edit(avatar=f.read())
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(f"updateStatus: {e} - line {exc_tb.tb_lineno} {fname}")
await asyncio.sleep(120)
async def createMessage(self, image_url: str, newstatus, title: str, description: str):
file = discord.File(f"{image_url}.png", filename=f"{image_url}.png")
channel = self.get_channel(MESSAGE_CHANNEL)
embed = discord.Embed(color=0xFFA500, title=title, description=description)
embed.set_footer(
text=f"player threshold set to {MIN_PLAYER_AMOUNT} players, checks difference of previous {(AMOUNT_OF_PREVIOUS_REQUESTS*2)} minutes and in-between"
)
embed.set_thumbnail(url=f"attachment://{image_url}.png") # small image
# embed.set_image(url=f"attachment://{image_url}.png") # bigger image
await channel.send(embed=embed, file=file)
async def get_playercount(session: aiohttp.ClientSession):
if GAME in ["bf2042", "bfv", "bf1", "bf4", "bf3", "bfh"]:
try:
url = f"https://api.gametools.network/{GAME}/detailedserver?name={urllib.parse.quote(NAME)}&lang={LANG}"
async with session.get(url=url) as r:
response = await r.json()
# results
players = (
response.get("noBotsPlayerAmount", 0)
if NO_BOTS and GAME == "bf4"
else response.get("playerAmount", 0)
)
maxPlayers = response.get("maxPlayerAmount", 0)
inQue = response.get("inQueue", 0)
serverMap = response.get("currentMap", "")
prefix = response.get("prefix", "")[0:30]
url = response.get("currentMapImage", "")
mode = response.get("mode", "")
except Exception as e:
print(f"Server not found or api.gametools.network unreachable - {e}")
return
else:
try:
url = f"https://api.gametools.network/{GAME}/servers?name={urllib.parse.quote(NAME)}&lang={LANG}"
async with session.get(url=url) as r:
response = await r.json()
first_result = response.get("servers", [])[0]
players = first_result.get("playerAmount", 0)
maxPlayers = first_result.get("maxPlayers", 0)
inQue = first_result.get("inQueue", 0)
serverMap = first_result.get("map", "")
prefix = first_result.get("prefix", "")[0:30]
url = first_result.get("mapImage", "")
mode = first_result.get("mode", "")
except Exception as e:
print(f"Server not found or api.gametools.network unreachable - {e}")
return
try:
# dont allow names longer than 30 characters
serverInfo = (
f"{players}/{maxPlayers} [{inQue}] - {serverMap}" # discord status message
)
# create image with only map
async with session.get(url=url) as r:
image = await r.read()
file = open("map_image.png", "wb")
file.write(image)
file.close()
# create image with mapmode
smallmode = ""
if mode == "Conquest":
smallmode = "CQ"
elif mode == "Domination":
smallmode = "DM"
elif mode == "TugOfWar":
smallmode = "FL"
elif mode == "Rush":
smallmode = "RS"
elif mode == "BreakthroughLarge":
smallmode = "OP"
elif mode == "Breakthrough":
smallmode = "SO"
elif mode == "Possession":
smallmode = "WP"
elif mode == "TeamDeathMatch":
smallmode = "TM"
# creating the images:
img = Image.open("map_image.png")
img = img.convert("RGBA")
tint = Image.new("RGBA", (img.width, img.height), (0, 0, 0, 80))
img = Image.alpha_composite(img, tint)
font = ImageFont.truetype(BIGFONT, size=130, index=0)
smallFont = ImageFont.truetype(SMALLFONT, size=35, index=0)
favoritesFont = ImageFont.truetype(SMALLFONT, size=60, index=0)
# draw smallmode
draw = ImageDraw.Draw(img)
_, _, w, h = draw.textbbox((0, 0), smallmode, font=font)
draw.text(
((img.width - w) / 2, (img.height - h - 50) / 2), smallmode, font=font
)
img.save("map_mode.png")
serverBookmarkCount = 0
# get favorites
if GAME in ["bf2042", "bf1", "bf4", "bf3", "bfh"]:
serverBookmarkCount = response.get("favorites", 0)
# draw bookmark
img = Image.open("map_mode.png")
draw = ImageDraw.Draw(img)
serverCountMessage = "\u2605" + serverBookmarkCount
_, _, w, h = draw.textbbox((0, 0), serverCountMessage, font=smallFont)
draw.text(
((img.width - w) / 2 - 40, (img.height - h + 160) / 2),
serverCountMessage,
font=smallFont,
)
img.save("avatar_image.png")
# draw infoImage
img = Image.open("map_mode.png")
draw = ImageDraw.Draw(img)
if GAME in ["bf2042", "bf1", "bf4", "bf3", "bfh"]:
serverCountMessage = f"\u2605{serverBookmarkCount}"
_, _, w, h = draw.textbbox((0, 0), serverCountMessage, font=smallFont)
draw.text(
((img.width - w) / 2, (img.height - h + 160) / 2),
serverCountMessage,
font=smallFont,
)
img.save("info_image.png")
# draw bookmark
img = Image.open("map_image.png")
img = img.convert("RGBA")
tint = Image.new("RGBA", (img.width, img.height), (0, 0, 0, 80))
img = Image.alpha_composite(img, tint)
draw = ImageDraw.Draw(img)
if GAME in ["bf2042", "bf1", "bf4", "bf3", "bfh"]:
serverCountMessage = f"\u2605{serverBookmarkCount}"
_, _, w, h = draw.textbbox((0, 0), serverCountMessage, font=favoritesFont)
draw.text(
((img.width - w) / 2, (img.height - h) / 2),
serverCountMessage,
font=favoritesFont,
)
img.save("only_favorites_image.png")
return {
"serverInfo": serverInfo,
"serverName": prefix,
"serverMap": serverMap,
"playerAmount": inQue + players,
}
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(f"playerList: {e} - line {exc_tb.tb_lineno} {fname}")
if __name__ == "__main__":
assert sys.version_info >= (3, 6), "Script requires Python 3.6+"
assert BOT_TOKEN and NAME, "Config is empty, pls fix"
assert os.path.exists(BIGFONT), "fontfile not found"
assert os.path.exists(SMALLFONT), "fontfile not found"
print("Initiating bot")
intents = discord.Intents.default()
LivePlayercountBot(intents=intents).run(BOT_TOKEN)