1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-23 19:44:20 +00:00

coseeeeeeeeeeeeeeeeeeeeee

This commit is contained in:
Steffo 2017-11-11 18:55:13 +01:00
parent 7b1674b511
commit dae3ee2649
WARNING! Although there is a key with this ID in the database it does not verify this commit! This commit is SUSPICIOUS.
GPG key ID: C27544372FBB445D
6 changed files with 106 additions and 88 deletions

24
db.py
View file

@ -598,30 +598,6 @@ class Diario(Base):
session.close()
class CVMusic(Base):
__tablename__ = "cvmusic"
id = Column(BigInteger, primary_key=True)
url = Column(String, nullable=False)
enqueued = Column(DateTime, nullable=False)
started = Column(DateTime, nullable=False)
user_id = Column(Integer, ForeignKey("royals.id"))
user = relationship("Royal")
@staticmethod
def create_and_add(url: str, user: Royal, enqueued: datetime.datetime, started: datetime.datetime):
try:
session = Session()
session.add(CVMusic(url=url,
enqueued=enqueued,
started=started,
user_id=user.id))
session.commit()
session.close()
except Exception as e:
print(f"ERRORE CVMusic: {e}")
# If run as script, create all the tables in the db
if __name__ == "__main__":
Base.metadata.create_all(bind=engine)

View file

@ -1,4 +1,5 @@
import datetime
import random
import discord
import discord.opus
import functools
@ -6,7 +7,6 @@ import sys
import db
import errors
import youtube_dl
import sqlalchemy.exc
# Init the event loop
import asyncio
@ -17,6 +17,18 @@ import configparser
config = configparser.ConfigParser()
config.read("config.ini")
# Find the latest git tag
import subprocess
import os
old_wd = os.getcwd()
try:
os.chdir(os.path.dirname(__file__))
version = str(subprocess.check_output(["git", "describe", "--tags"]), encoding="utf8").strip()
except:
version = "v???"
finally:
os.chdir(old_wd)
# Init the discord bot
client = discord.Client()
discord.opus.load_opus("libopus-0.dll")
@ -26,6 +38,7 @@ voice_queue = []
voice_playing = None
class Video:
def __init__(self):
self.user = None
@ -51,13 +64,13 @@ class Video:
def create_embed(self):
embed = discord.Embed(type="rich",
title=self.info['title'] if 'title' in self.info else None,
url=self.info['webpage_url'] if 'webpage_url' in self.info else None,
title=self.info.get("title"),
url=self.info.get("webpage_url"),
colour=discord.Colour(13375518))
# Uploader
if "uploader" in self.info and self.info["uploader"] is not None:
if self.info.get("uploader"):
embed.set_author(name=self.info["uploader"],
url=self.info["uploader_url"] if "uploader_url" in self.info else None)
url=self.info.get("uploader_url"))
# Thumbnail
if "thumbnail" in self.info:
embed.set_thumbnail(url=self.info["thumbnail"])
@ -107,6 +120,7 @@ async def on_error(event, *args, **kwargs):
f"```python\n"
f"{repr(exception)}\n"
f"```")
await voice_client.disconnect()
await client.change_presence(status=discord.Status.invisible)
await client.close()
except Exception as e:
@ -117,7 +131,7 @@ async def on_error(event, *args, **kwargs):
@client.event
async def on_ready():
await client.send_message(client.get_channel("368447084518572034"), f" Bot avviato e pronto a ricevere comandi!")
await client.send_message(client.get_channel("368447084518572034"), f" Royal Bot {version} avviato e pronto a ricevere comandi!")
await client.change_presence(game=None, status=discord.Status.online)
@ -145,7 +159,7 @@ async def on_message(message: discord.Message):
session.commit()
session.close()
await client.send_message(message.channel, "✅ Sincronizzazione completata!")
elif message.content.startswith("!cv") and discord.opus.is_loaded():
elif message.content.startswith("!cv"):
await client.send_typing(message.channel)
if message.author.voice.voice_channel is None:
await client.send_message(message.channel, "⚠ Non sei in nessun canale!")
@ -168,7 +182,7 @@ async def on_message(message: discord.Message):
url = message.content.split(" ", 1)[1]
except IndexError:
await client.send_message(message.channel, "⚠️ Non hai specificato un url!\n"
"Sintassi corretta: `!madd <video>`")
"Sintassi corretta: `!play <video>`")
return
# Se è una playlist, informa che potrebbe essere richiesto un po' di tempo
if "playlist" in url:
@ -181,7 +195,12 @@ async def on_message(message: discord.Message):
except youtube_dl.utils.DownloadError as e:
if "is not a valid URL" in str(e) or "Unsupported URL" in str(e):
await client.send_message(message.channel, f"⚠️ Il link inserito non è valido.\n"
f"Se vuoi cercare un video su YouTube, usa `!msearch <query>`")
f"Se vuoi cercare un video su YouTube, usa `!search <query>`")
else:
await client.send_message(message.channel, f"⚠ Errore:\n"
f"```\n"
f"{e}"
f"```")
return
if "_type" not in info:
# If target is a single video
@ -222,7 +241,7 @@ async def on_message(message: discord.Message):
text = message.content.split(" ", 1)[1]
except IndexError:
await client.send_message(message.channel, "⚠️ Non hai specificato il titolo!\n"
"Sintassi corretta: `!msearch <titolo>`")
"Sintassi corretta: `!search <titolo>`")
return
# Extract the info from the url
try:
@ -247,7 +266,7 @@ async def on_message(message: discord.Message):
return
voice_player.pause()
await client.send_message(message.channel, f"⏸ Riproduzione messa in pausa.\n"
f"Riprendi con `!mresume`.")
f"Riprendi con `!resume`.")
elif message.content.startswith("!resume"):
if voice_player is None or voice_player.is_playing():
await client.send_message(message.channel, f"⚠️ Non c'è nulla in pausa da riprendere!")
@ -289,6 +308,27 @@ async def on_message(message: discord.Message):
to_send = to_send[0:1997] + "..."
break
await client.send_message(message.channel, to_send)
elif message.content.startswith("!cast"):
try:
spell = message.content.split(" ", 1)[1]
except IndexError:
await client.send_message("⚠️ Non hai specificato nessun incantesimo!\n"
"Sintassi corretta: `!cast <nome_incantesimo>`")
return
target = random.sample(list(message.server.members), 1)[0]
# Seed the rng with the spell name
# so that spells always deal the same damage
random.seed(spell)
dmg_mod = random.randrange(-2, 3)
dmg_dice = random.randrange(1, 4)
dmg_max = random.sample([4, 6, 8, 10, 12, 20, 100], 1)[0]
# Reseed the rng with a random value
# so that the dice roll always deals a different damage
random.seed()
total = dmg_mod
for dice in range(0, dmg_dice):
total += random.randrange(1, dmg_max+1)
await client.send_message(message.channel, f"❇️ Ho lanciato **{spell}** su **{target.nick if target.nick is not None else target.name}** per {dmg_dice}d{dmg_max}{'+' if dmg_mod > 0 else ''}{str(dmg_mod) if dmg_mod != 0 else ''}=**{total if total > 0 else 0}** danni!")
elif __debug__ and message.content.startswith("!exception"):
raise Exception("!exception was called")
@ -332,8 +372,6 @@ async def update_music_queue():
# Set the playing status
voice_playing = video
await client.change_presence(game=discord.Game(name=video.info.get("title"), type=2))
# Add the video to the db
await loop.run_in_executor(None, functools.partial(video.add_to_db, started=datetime.datetime.now()))
def process(users_connection):

View file

@ -27,8 +27,8 @@ table.dota {
color: white !important;
}
th.dota {
border-bottom: 4px solid #6BF !important;
table.dota th {
border-bottom: 1px solid #666 !important;
}
.rl-rank-hidden {

View file

@ -1,3 +1,7 @@
import random
import math
import db
import errors
from telegram import Bot, Update, Message
@ -9,7 +13,20 @@ import configparser
config = configparser.ConfigParser()
config.read("config.ini")
users_connection = None
discord_connection = None
# Find the latest git tag
import subprocess
import os
old_wd = os.getcwd()
try:
os.chdir(os.path.dirname(__file__))
version = str(subprocess.check_output(["git", "describe", "--tags"]), encoding="utf8").strip()
except:
version = "v???"
finally:
os.chdir(old_wd)
def cmd_register(bot: Bot, update: Update):
session = db.Session()
@ -32,8 +49,8 @@ def cmd_register(bot: Bot, update: Update):
def cmd_discord(bot: Bot, update: Update):
users_connection.send("/cv")
server_members = users_connection.recv()
discord_connection.send("/cv")
server_members = discord_connection.recv()
message = ""
for member in server_members:
if member.status == DiscordStatus.offline and member.voice.voice_channel is None:
@ -73,12 +90,41 @@ def cmd_discord(bot: Bot, update: Update):
bot.send_message(update.message.chat.id, message, disable_web_page_preview=True, parse_mode="Markdown")
def process(discord_users_connection):
def cmd_cast(bot: Bot, update: Update):
try:
spell = update.message.text.split(" ", 1)[1]
except IndexError:
bot.send_message(update.message.chat.id, "⚠️ Non hai specificato nessun incantesimo!\n"
"Sintassi corretta: `/cast <nome_incantesimo>`")
return
# Open a new db session
session = db.Session()
# Find a target for the spell
target = random.sample(session.query(db.Telegram).all(), 1)[0]
# Close the session
session.close()
# Seed the rng with the spell name
# so that spells always deal the same damage
random.seed(spell)
dmg_dice = random.randrange(1, 11)
dmg_max = random.sample([4, 6, 8, 10, 12, 20, 100], 1)[0]
dmg_mod = random.randrange(math.floor(-dmg_max / 5), math.ceil(dmg_max / 5) + 1)
# Reseed the rng with a random value
# so that the dice roll always deals a different damage
random.seed()
total = dmg_mod
for dice in range(0, dmg_dice):
total += random.randrange(1, dmg_max + 1)
bot.send_message(update.message.chat.id, f"❇️ Ho lanciato {spell} su {target.username if target.username is not None else target.first_name} per {dmg_dice}d{dmg_max}{'+' if dmg_mod > 0 else ''}{str(dmg_mod) if dmg_mod != 0 else ''}={total if total > 0 else 0} danni!")
def process(arg_discord_connection):
print("Telegrambot starting...")
global users_connection
users_connection = discord_users_connection
global discord_connection
discord_connection = arg_discord_connection
u = Updater(config["Telegram"]["bot_token"])
u.dispatcher.add_handler(CommandHandler("register", cmd_register))
u.dispatcher.add_handler(CommandHandler("discord", cmd_discord))
u.dispatcher.add_handler(CommandHandler("cast", cmd_cast))
u.start_polling()
u.idle()

View file

@ -1,34 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Leaderboards - RYG</title>
<script src="{{ url_for('static', filename='sorttable.js') }}"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"
integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link rel="stylesheet" href="{{ url_for('static', filename='royal.css') }}">
</head>
<body>
<div class="container">
<h1>
Top Plays
</h1>
<table class="table table-hover sortable">
<thead>
<tr>
<th>URL</th>
<th>Plays</th>
</tr>
</thead>
<tbody>
{% for record in top_plays %}
<tr>
<td><a href="{{ record[0] }}">{{ record[0] }}</a></td>
<td>{{ record[1] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>

View file

@ -1,5 +1,5 @@
from flask import Flask, render_template
from db import Session, Royal, Steam, RocketLeague, Dota, Osu, Overwatch, LeagueOfLegends, CVMusic
from db import Session, Royal, Steam, RocketLeague, Dota, Osu, Overwatch, LeagueOfLegends
from sqlalchemy.orm import joinedload
from sqlalchemy import func
@ -20,14 +20,6 @@ def page_leaderboards():
return render_template("leaderboards.html", dota_data=dota_data, rl_data=rl_data, ow_data=ow_data, osu_data=osu_data, lol_data=lol_data)
@app.route("/music")
def page_music():
session = Session()
top_plays = session.execute("SELECT cvmusic.url, COUNT(cvmusic.url) FROM cvmusic GROUP BY cvmusic.url ORDER BY COUNT(cvmusic.url);").fetchall()
session.close()
return render_template("music.html", top_plays=top_plays)
if __name__ == "__main__":
try:
app.run(host="0.0.0.0", port=1234, debug=True)