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

Merge remote-tracking branch 'origin/master'

This commit is contained in:
Steffo 2017-03-29 09:16:01 +02:00
commit c6e34f6ae1
3 changed files with 79 additions and 14 deletions

View file

@ -1,3 +1,4 @@
import sqlalchemy.exc
from sqlalchemy import create_engine, Column, Integer, String, Boolean from sqlalchemy import create_engine, Column, Integer, String, Boolean
from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative import declarative_base
@ -90,7 +91,7 @@ def login(username, password, enable_exceptions=False):
def init_royal_db(): def init_royal_db():
create_user("test", "test", False) create_user("test", "test", True)
session = Session() session = Session()
# Generate the database if it's empty # Generate the database if it's empty

View file

@ -479,7 +479,7 @@ Sintassi: `/roll <max>`"""
parse_mode="Markdown") parse_mode="Markdown")
return return
# Roll the dice! # Roll the dice!
await update.message.reply(bot, f"*Numero generato:* {random.randrange(0, int(arguments[0])) + 1}") await update.message.reply(bot, f"*Numero generato:* {random.randrange(0, int(arguments[0])) + 1}", parse_mode="Markdown")
async def roll_discord(bot, message, arguments): async def roll_discord(bot, message, arguments):
@ -494,6 +494,70 @@ Sintassi: `!roll <max>`"""
await bot.send_message(message.channel, f"*Numero generato:* {random.randrange(0, int(arguments[0])) + 1}") await bot.send_message(message.channel, f"*Numero generato:* {random.randrange(0, int(arguments[0])) + 1}")
async def adduser_telegram(bot, update, arguments):
"""Aggiungi un utente al database Royal Games!
Devi essere un Royal per poter eseguire questo comando.
Sintassi: `/adduser <username> <password>`"""
# Check if the user is logged in
if not currently_logged_in(update):
await update.message.reply(bot, "⚠ Non hai ancora eseguito l'accesso! Usa `/sync`.", parse_mode="Markdown")
return
# Check if the currently logged in user is a Royal Games member
if not currently_logged_in(update).royal:
await update.message.reply(bot, "⚠ Non sei autorizzato a eseguire questo comando.")
return
# Check the command syntax
if len(arguments) != 2:
await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/adduser <username> <password>`", parse_mode="Markdown")
return
# Try to create a new user
try:
database.create_user(arguments[0], arguments[1], False)
except database.sqlalchemy.exc.DBAPIError:
await update.message.reply(bot, "⚠ Qualcosa è andato storto nella creazione dell'utente. Per altre info, guarda i log del bot.")
raise
else:
await update.message.reply(bot, "✅ Creazione riuscita!")
async def toggleroyal_telegram(bot, update, arguments):
"""Inverti lo stato di Royal di un utente.
Devi essere un Royal per poter eseguire questo comando.
Sintassi: `/toggleroyal <username>`"""
# Check if the user is logged in
if not currently_logged_in(update):
await update.message.reply(bot, "⚠ Non hai ancora eseguito l'accesso! Usa `/sync`.", parse_mode="Markdown")
return
# Check if the currently logged in user is a Royal Games member
if not currently_logged_in(update).royal:
await update.message.reply(bot, "⚠ Non sei autorizzato a eseguire questo comando.")
return
# Check the command syntax
if len(arguments) != 1:
await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/toggleroyal <username>`", parse_mode="Markdown")
return
# Create a new database session
session = database.Session()
# Find the user
user = session.query(database.User).filter_by(username=arguments[0]).first()
# Check if the user exists
if user is None:
await update.message.reply(bot, "⚠ L'utente specificato non esiste.")
return
# Toggle his Royal status
user.royal = not user.royal
# Save the change
session.commit()
# Answer on Telegram
if user.royal:
await update.message.reply(bot, f"✅ L'utente `{user.username}` ora è un Royal.", parse_mode="Markdown")
else:
await update.message.reply(bot, f"✅ L'utente `{user.username}` non è più un Royal.", parse_mode="Markdown")
if __name__ == "__main__": if __name__ == "__main__":
# Init Telegram bot commands # Init Telegram bot commands
b.commands["start"] = start_telegram b.commands["start"] = start_telegram
@ -506,6 +570,8 @@ if __name__ == "__main__":
b.commands["markov"] = markov_telegram b.commands["markov"] = markov_telegram
b.commands["cv"] = cv_telegram b.commands["cv"] = cv_telegram
b.commands["roll"] = roll_telegram b.commands["roll"] = roll_telegram
b.commands["adduser"] = adduser_telegram
b.commands["toggleroyal"] = toggleroyal_telegram
# Init Discord bot commands # Init Discord bot commands
d.commands["sync"] = sync_discord d.commands["sync"] = sync_discord
d.commands["roll"] = roll_discord d.commands["roll"] = roll_discord

View file

@ -5,7 +5,11 @@ import datetime
class TelegramAPIError(Exception): class TelegramAPIError(Exception):
pass def __init__(self, code, description):
# Error code
self.code = code
# Error description
self.description = description
class UpdateError(Exception): class UpdateError(Exception):
@ -59,7 +63,7 @@ class Bot:
self.updates.append(Update(update)) self.updates.append(Update(update))
except NotImplementedError: except NotImplementedError:
pass pass
if len(data) > 0: if len(self.updates) > 0:
self.offset = self.updates[-1].update_id + 1 self.offset = self.updates[-1].update_id + 1
async def parse_update(self, update): async def parse_update(self, update):
@ -142,14 +146,8 @@ class Bot:
# Parse the json data as soon it's ready # Parse the json data as soon it's ready
data = await response.json() data = await response.json()
# Check for errors in the request # Check for errors in the request
if "description" in data: if response.status != 200 or not data["ok"]:
error = data["description"] raise TelegramAPIError(data["error_code"], data["description"])
if response.status != 200:
raise TelegramAPIError(f"Request returned {response.status} {response.reason}")
# Check for errors in the response
if not data["ok"]:
error = data["description"]
raise TelegramAPIError(f"Response returned an error: {error}")
# Return a dictionary containing the data # Return a dictionary containing the data
return data["result"] return data["result"]