- New command $osu_profile <username> ! + Massive file tree reorganization + Updated the readme

This commit is contained in:
Florian SYLVAIN
2021-02-11 16:01:41 +01:00
parent f92f70d017
commit c1a1bc23d3
8 changed files with 245 additions and 189 deletions
+13 -2
View File
@@ -15,11 +15,15 @@
<br> <br>
![](chat_record1.gif) ![](assets/chat_record1.gif)
<br> <br>
![](rank_record.gif) ![](assets/rank_record.gif)
<br>
![](assets/osu_record.gif)
<br> <br>
@@ -54,6 +58,13 @@ $rank {lol_username}
``` ```
This command will display a message with the current League of Legend rank of the EUW account you ask for. Make sure to use quotes if there is spaces in the LoL username. This command will display a message with the current League of Legend rank of the EUW account you ask for. Make sure to use quotes if there is spaces in the LoL username.
### **osu_profile**
```
$osu_profile {osu_username}
```
This command will display a message with all the (basics) stats from the Osu! profile you ask for.
<br> <br>
# ⚙ Configuration # ⚙ Configuration

Before

Width:  |  Height:  |  Size: 226 KiB

After

Width:  |  Height:  |  Size: 226 KiB

View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Before

Width:  |  Height:  |  Size: 100 KiB

After

Width:  |  Height:  |  Size: 100 KiB

+196 -166
View File
@@ -1,166 +1,196 @@
import asyncio import asyncio
import socket import socket
import re import re
import discord import discord
from private import * from private import *
from discord.ext import tasks, commands from discord.ext import tasks, commands
from riot_api import rank_track, WATCHER, REGION from riot_api import rank_track, WATCHER, REGION
from riotwatcher import ApiError from riotwatcher import ApiError
from emoji import demojize from emoji import demojize
from twitch import TwitchClient from twitch import TwitchClient
from osu_api import ask_osu
bot = commands.Bot(command_prefix='$')
twitch_client = TwitchClient(client_id=ID_TWITCH, oauth_token=TOKEN_TWITCH) bot = commands.Bot(command_prefix='$')
chats = dict() twitch_client = TwitchClient(client_id=ID_TWITCH, oauth_token=TOKEN_TWITCH)
chats = dict()
class ChatObj:
def __init__(self, twitch_user, discord_channel): class ChatObj:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def __init__(self, twitch_user, discord_channel):
self.twitch_user = twitch_user self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.discord_channel = discord_channel self.twitch_user = twitch_user
chats[discord_channel] = self self.discord_channel = discord_channel
chats[discord_channel] = self
def chat_init(self):
try: def chat_init(self):
self.sock.connect((SERVER, PORT)) try:
self.sock.send(f"PASS {TOKEN_TWITCH}\n".encode('utf-8')) self.sock.connect((SERVER, PORT))
self.sock.send(f"NICK {NICKNAME}\n".encode('utf-8')) self.sock.send(f'PASS {TOKEN_TWITCH}\n'.encode('utf-8'))
self.sock.send(f"JOIN {'#' + self.twitch_user}\n".encode('utf-8')) self.sock.send(f'NICK {NICKNAME}\n'.encode('utf-8'))
self.sock.settimeout(0.0) self.sock.send(f"JOIN {'#' + self.twitch_user}\n".encode('utf-8'))
self.sock.setblocking(False) self.sock.settimeout(0.0)
return 1 self.sock.setblocking(False)
except OSError: return 1
return 0 except OSError:
return 0
@tasks.loop(seconds=1)
async def twitch(self): @tasks.loop(seconds=1)
await bot.wait_until_ready() async def twitch(self):
try: await bot.wait_until_ready()
resp = self.sock.recv(2048).decode('utf-8') try:
except socket.error: resp = self.sock.recv(2048).decode('utf-8')
resp = '' except socket.error:
resp = ''
if resp.startswith('PING'):
self.sock.send("PONG\n".encode('utf-8')) if resp.startswith('PING'):
self.sock.send('PONG\n'.encode('utf-8'))
elif len(resp) > 0:
try: elif len(resp) > 0:
chain = re.search(r':(.*)\!.*@.*\.tmi\.twitch\.tv PRIVMSG #(.*) :(.*)', demojize(resp)) try:
username = chain.group(1) chain = re.search(r':(.*)\!.*@.*\.tmi\.twitch\.tv PRIVMSG #(.*) :(.*)', demojize(resp))
message = chain.group(3) username = chain.group(1)
msg = f"**__{username}__ :** {message}" message = chain.group(3)
await self.discord_channel.send(msg) msg = f'**__{username}__ :** {message}'
except discord.DiscordException: await self.discord_channel.send(msg)
pass except discord.DiscordException:
except AttributeError: pass
pass except AttributeError:
pass
@twitch.after_loop
async def after_twitch(self): @twitch.after_loop
self.sock.shutdown(1) async def after_twitch(self):
try: self.sock.shutdown(1)
self.sock.close() try:
except OSError: self.sock.close()
pass except OSError:
pass
def check_user(name):
user = twitch_client.users.translate_usernames_to_ids([name]) def check_user(name):
if not user: user = twitch_client.users.translate_usernames_to_ids([name])
return False if not user:
return True return False
return True
async def del_message(ctx):
try: async def del_message(ctx):
await ctx.message.delete() try:
except discord.errors.Forbidden: await ctx.message.delete()
pass except discord.errors.Forbidden:
pass
@bot.event
async def on_ready(): @bot.event
default_activity = discord.Activity(type=discord.ActivityType.listening, name="$help") async def on_ready():
await bot.change_presence(activity=default_activity) default_activity = discord.Activity(type=discord.ActivityType.listening, name='$help')
print('We have logged in as {0.user}'.format(bot)) await bot.change_presence(activity=default_activity)
print('We have logged in as {0.user}'.format(bot))
@bot.command()
async def chat_set(ctx, arg1): @bot.command()
await del_message(ctx) async def chat_set(ctx, arg1):
what_channel = ctx.channel await del_message(ctx)
if what_channel in list(chats): what_channel = ctx.channel
await ctx.send("```A chat is already active, you have to stop it before with the cmd $chat_stop !```") if what_channel in list(chats):
else: await ctx.send("```A chat is already active, you have to stop it before with the cmd $chat_stop !```")
if check_user(arg1): else:
obj = ChatObj(arg1, what_channel) if check_user(arg1):
if obj.chat_init(): obj = ChatObj(arg1, what_channel)
await ctx.send(f'```Now connected to {arg1}\'s twitch channel !```') if obj.chat_init():
obj.twitch.start() await ctx.send(f'```Now connected to {arg1}\'s twitch channel !```')
else: obj.twitch.start()
await ctx.send('```Something went wrong when trying to access Twitch IRC.```') else:
else: await ctx.send('```Something went wrong when trying to access Twitch IRC.```')
await ctx.send('```This twitch channel doesn\'t seems to exist.```') else:
await ctx.send('```This twitch channel doesn\'t seems to exist.```')
@bot.command()
async def chat_stop(ctx): @bot.command()
await del_message(ctx) async def chat_stop(ctx):
chan = ctx.channel await del_message(ctx)
if chan in list(chats): chan = ctx.channel
chats[chan].twitch.stop() if chan in list(chats):
del chats[chan] chats[chan].twitch.stop()
await asyncio.sleep(1) del chats[chan]
message = '```The chat was successfully stopped !```' await asyncio.sleep(1)
else: message = '```The chat was successfully stopped !```'
message = '```There is no active chat in this channel.```' else:
await ctx.send(message) message = '```There is no active chat in this channel.```'
await ctx.send(message)
@bot.command()
async def rank(ctx, arg, argf=None): @bot.command()
await del_message(ctx) async def rank(ctx, arg, argf=None):
if argf is None: await del_message(ctx)
try: if argf is None:
player = WATCHER.summoner.by_name(REGION, arg) try:
ranks = rank_track(player) player = WATCHER.summoner.by_name(REGION, arg)
embed = discord.Embed(title=arg, url="https://www.youtube.com/watch?v=dQw4w9WgXcQ") ranks = rank_track(player)
embed.set_thumbnail(url="http://ddragon.leagueoflegends.com/cdn/11.2.1/img/profileicon/" + str( embed = discord.Embed(title=arg, url='https://www.youtube.com/watch?v=dQw4w9WgXcQ')
player['profileIconId']) + ".png") embed.set_thumbnail(url='http://ddragon.leagueoflegends.com/cdn/11.2.1/img/profileicon/' + str(
if isinstance(ranks, list): player['profileIconId']) + '.png')
for rank_s in ranks: embed.set_author(name='League Of Legend', url='https://euw.leagueoflegends.com/en-gb/',
embed.add_field(name=rank_s[0], value=str(rank_s[1]) + ' ' + str(rank_s[2]) + ' ' + str( icon_url='https://static.wikia.nocookie.net/leagueoflegends/images/0/07/' +
rank_s[3]) + ' LP' + '\n' + str(rank_s[4]) + 'W/' + str(rank_s[5]) + 'L', inline=False) 'League_of_Legends_icon.png/revision/latest?cb=20191018194326')
else: if isinstance(ranks, list):
embed.description = ranks for rank_s in ranks:
await ctx.send(embed=embed) embed.add_field(name=rank_s[0], value=str(rank_s[1]) + ' ' + str(rank_s[2]) + ' ' + str(
except ApiError: rank_s[3]) + ' LP' + '\n' + str(rank_s[4]) + 'W/' + str(rank_s[5]) + 'L', inline=False)
await ctx.send("The nickname is unknown.") else:
else: embed.description = ranks
await ctx.send("If you are trying to use a nickname with spaces, please surround it with quotes.") await ctx.send(embed=embed)
except ApiError:
await ctx.send('The username you entered is unknown.')
@bot.command() else:
async def issou(ctx, arg1: discord.User = None): await ctx.send('If you are trying to use a username you entered with spaces, please surround it with quotes.')
if arg1 is not None:
user = arg1
else: @bot.command()
user = ctx.message.author async def issou(ctx, arg1: discord.User = None):
await del_message(ctx) if arg1 is not None:
try: user = arg1
voice_channel = user.voice.channel else:
except AttributeError: user = ctx.message.author
voice_channel = None await del_message(ctx)
try:
if voice_channel is not None: voice_channel = user.voice.channel
voice = await voice_channel.connect() except AttributeError:
voice.play(discord.FFmpegPCMAudio('issou.mp3')) voice_channel = None
if voice.is_playing():
await asyncio.sleep(1) if voice_channel is not None:
await voice.disconnect() voice = await voice_channel.connect()
else: voice.play(discord.FFmpegPCMAudio('../assets/issou.mp3'))
await ctx.send('You or the targeted person are not connected to any channel.') if voice.is_playing():
await asyncio.sleep(1)
await voice.disconnect()
bot.run(TOKEN_BOT) else:
await ctx.send('You or the targeted person are not connected to any channel.')
@bot.command()
async def osu_profile(ctx, arg):
await del_message(ctx)
lst = await ask_osu(arg)
if lst == 1:
await ctx.send('The username you entered is unknown.')
else:
embed = discord.Embed(title=arg, url='https://osu.ppy.sh/users/' + str(lst[0]))
embed.set_thumbnail(url='https://a.ppy.sh/' + str(lst[0]))
embed.set_author(name='Osu!', url='https://osu.ppy.sh/home',
icon_url=r'https://upload.wikimedia.org/wikipedia/commons/4/44/Osu%21Logo_%282019%29.png')
embed.add_field(name='Global Ranking', value='#'+str('{:,}'.format(lst[8])))
embed.add_field(name='Total Play Time', value=
str("%.0f" % ((lst[6] % (86400 * 30)) / 86400))+'d '+
str("%.0f" % ((lst[6] % 86400) / 3600))+'h '+
str("%.0f" % ((lst[6] % 3600) / 60))+'m ')
embed.add_field(name='Level', value=str("%.0f" % lst[7]))
embed.add_field(name='Ranked Score', value=str('{:,}'.format(lst[1])))
embed.add_field(name='Hit Accuracy', value=str("%.2f" % lst[2])+'%')
embed.add_field(name='Play Count', value=str('{:,}'.format(lst[3])))
embed.add_field(name='Total Score', value=str('{:,}'.format(lst[4])))
embed.add_field(name='Total Hits', value=str('{:,}'.format(lst[5])))
await ctx.send(embed=embed)
bot.run(TOKEN_BOT)
+15
View File
@@ -0,0 +1,15 @@
from osuapi import OsuApi, ReqConnector
from private import TOKEN_OSU
import requests
api = OsuApi(TOKEN_OSU, connector=ReqConnector())
async def ask_osu(username):
results = api.get_user(username)
if not results:
return 1
r = results[0]
liste = [r.user_id, r.ranked_score, r.accuracy, r.playcount,
r.total_score, (r.count300 + r.count100 + r.count50),
r.total_seconds_played, r.level, r.pp_rank]
return liste
+21 -21
View File
@@ -1,21 +1,21 @@
from riotwatcher import LolWatcher from riotwatcher import LolWatcher
from private import TOKEN_RIOT from private import TOKEN_RIOT
WATCHER = LolWatcher(TOKEN_RIOT) WATCHER = LolWatcher(TOKEN_RIOT)
REGION = 'EUW1' REGION = 'EUW1'
def rank_track(player): def rank_track(player):
'''function that communicate with Riot API''' '''function that communicate with Riot API'''
ranked_stats = WATCHER.league.by_summoner(REGION, player['id']) ranked_stats = WATCHER.league.by_summoner(REGION, player['id'])
if not ranked_stats: if not ranked_stats:
return 'Unranked cette saison.' return 'Unranked cette saison.'
liste = [] liste = []
for infos in ranked_stats: for infos in ranked_stats:
if infos['queueType'] == 'RANKED_SOLO_5x5': if infos['queueType'] == 'RANKED_SOLO_5x5':
what_rank = 'Solo Queue' what_rank = 'Solo Queue'
elif infos['queueType'] == 'RANKED_FLEX_SR': elif infos['queueType'] == 'RANKED_FLEX_SR':
what_rank = 'Flexible' what_rank = 'Flexible'
liste.append([what_rank, infos['tier'], infos['rank'], infos['leaguePoints'], infos['wins'], infos['losses']]) liste.append([what_rank, infos['tier'], infos['rank'], infos['leaguePoints'], infos['wins'], infos['losses']])
return liste return liste