First functional but alpha stage release

This commit is contained in:
spla 2020-11-16 17:54:46 +01:00
commit 21242eddfa
S'han modificat 5 arxius amb 1554 adicions i 0 eliminacions

31
README.md Normal file
Veure arxiu

@ -0,0 +1,31 @@
# Mastodon Chess
Play with other fediverse users a Chess game! Mastodon Chess control games, players and boards!
Usage:
To start a game:
@your_bot_username new
To make a move:
@your_bot_username move e2e4
### Dependencies
- **Python 3**
- Postgresql server
- Mastodon's bot account
### Usage:
Within Python Virtual Environment:
1. Run `pip install -r requirements.txt` to install needed Python libraries.
2. Run `python db-setup.py` to setup and create new Postgresql database and needed tables in it.
3. Run `python setup.py` to get your Mastodon's bot account tokens.
4. Use your favourite scheduling method to set `python mastochess.py` to run regularly.

174
db-setup.py Normal file
Veure arxiu

@ -0,0 +1,174 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import getpass
import os
import sys
from mastodon import Mastodon
from mastodon.Mastodon import MastodonMalformedEventError, MastodonNetworkError, MastodonReadTimeout, MastodonAPIError
import psycopg2
from psycopg2 import sql
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
# Returns the parameter from the specified file
def get_parameter( parameter, file_path ):
# Check if secrets file exists
if not os.path.isfile(file_path):
print("File %s not found, asking."%file_path)
write_parameter( parameter, file_path )
#sys.exit(0)
# Find parameter in file
with open( file_path ) as f:
for line in f:
if line.startswith( parameter ):
return line.replace(parameter + ":", "").strip()
# Cannot find parameter, exit
print(file_path + " Missing parameter %s "%parameter)
sys.exit(0)
def write_parameter( parameter, file_path ):
if not os.path.exists('config'):
os.makedirs('config')
print("Setting up chess parameters...")
print("\n")
chess_db = input("chess db name: ")
chess_db_user = input("chess db user: ")
mastodon_db = input("Mastodon database: ")
mastodon_db_user = input("Mastodon database user: ")
with open(file_path, "w") as text_file:
print("chess_db: {}".format(chess_db), file=text_file)
print("chess_db_user: {}".format(chess_db_user), file=text_file)
print("mastodon_db: {}".format(mastodon_db), file=text_file)
print("mastodon_db_user: {}".format(mastodon_db_user), file=text_file)
def create_table(db, db_user, table, sql):
conn = None
try:
conn = psycopg2.connect(database = db, user = db_user, password = "", host = "/var/run/postgresql", port = "5432")
cur = conn.cursor()
print("Creating table.. "+table)
# Create the table in PostgreSQL database
cur.execute(sql)
conn.commit()
print("Table "+table+" created!")
print("\n")
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
###############################################################################
# main
if __name__ == '__main__':
# Load configuration from config file
config_filepath = "config/db_config.txt"
mastodon_db = get_parameter("mastodon_db", config_filepath)
mastodon_db_user = get_parameter("mastodon_db_user", config_filepath)
chess_db = get_parameter("chess_db", config_filepath)
chess_db_user = get_parameter("chess_db_user", config_filepath)
############################################################
# create database
############################################################
conn = None
try:
conn = psycopg2.connect(dbname='postgres',
user=chess_db_user, host='',
password='')
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = conn.cursor()
print("Creating database " + chess_db + ". Please wait...")
cur.execute(sql.SQL("CREATE DATABASE {}").format(
sql.Identifier(chess_db))
)
print("Database " + chess_db + " created!")
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
############################################################
try:
conn = None
conn = psycopg2.connect(database = chess_db, user = chess_db_user, password = "", host = "/var/run/postgresql", port = "5432")
except (Exception, psycopg2.DatabaseError) as error:
print(error)
# Load configuration from config file
os.remove("config/db_config.txt")
print("Exiting. Run db-setup again with right parameters")
sys.exit(0)
finally:
if conn is not None:
conn.close()
print("\n")
print("chess parameters saved to db-config.txt!")
print("\n")
############################################################
# Create needed tables
############################################################
print("Creating table...")
db = chess_db
db_user = chess_db_user
table = "botreplies"
sql = "create table "+table+" (status_id bigint PRIMARY KEY, query_user varchar(40), status_created_at timestamptz)"
create_table(db, db_user, table, sql)
table = "games"
sql = "create table "+table+" (created_at timestamptz, game_id serial, white_user varchar(40), black_user varchar(40), chess_game varchar(200), "
sql +=" chess_status varchar(12), waiting boolean, updated_at timestamptz, next_move varchar(40), last_move varchar(40), moves int, finished boolean default False, PRIMARY KEY(game_id))"
create_table(db, db_user, table, sql)
table = "stats"
sql = "create table "+table+" (created_at timestamptz, game_id serial PRIMARY KEY, white_user varchar(40), black_user varchar(40), winner varchar(40), "
sql += "finished boolean default False, updated_at timestamptz, CONSTRAINT fk_game FOREIGN KEY(game_id) REFERENCES games(game_id) ON DELETE CASCADE ON UPDATE CASCADE)"
create_table(db, db_user, table, sql)
############################################################
print("Done!")
print("Now you can run setup.py!")
print("\n")

1106
mastochess.py Normal file

La diferencia del archivo ha sido suprimido porque es demasiado grande Cargar Diff

5
requirements.txt Normal file
Veure arxiu

@ -0,0 +1,5 @@
Mastodon.py>=1.5.1
chess>=1.3.0
psycopg2-binary>=2.8.6
unidecode>=1.1.1
cairosvg>=2.5.0

238
setup.py Normal file
Veure arxiu

@ -0,0 +1,238 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import getpass
from mastodon import Mastodon
from mastodon.Mastodon import MastodonMalformedEventError, MastodonNetworkError, MastodonReadTimeout, MastodonAPIError, MastodonIllegalArgumentError
import fileinput,re
import os
import sys
def create_dir():
if not os.path.exists('secrets'):
os.makedirs('secrets')
def create_file():
if not os.path.exists('secrets/secrets.txt'):
with open('secrets/secrets.txt', 'w'): pass
print(secrets_filepath + " created!")
def create_config():
if not os.path.exists('config'):
os.makedirs('config')
if not os.path.exists(config_filepath):
print(config_filepath + " created!")
with open('config/config.txt', 'w'): pass
def create_lang_config():
if not os.path.exists(lang_config_filepath):
print(lang_config_filepath + " created!")
with open('config/lang_config.txt', 'w'): pass
def write_params():
with open(secrets_filepath, 'a') as the_file:
print("Writing secrets parameter names to " + secrets_filepath)
the_file.write('uc_client_id: \n'+'uc_client_secret: \n'+'uc_access_token: \n')
def write_config():
with open(config_filepath, 'a') as the_file:
print("Writing parameters names 'mastodon_hostname' and 'bot_username' to " + config_filepath)
the_file.write('mastodon_hostname: \n' + 'bot_username: \n')
def write_lang_config():
with open(lang_config_filepath, 'a') as lang_file:
lang_file.write('bot_lang: \n')
print("adding Bot lang parameter name 'bot_lang' to "+ lang_config_filepath)
def read_client_lines(self):
client_path = 'app_clientcred.txt'
with open(client_path) as fp:
line = fp.readline()
cnt = 1
while line:
if cnt == 1:
print("Writing client id to " + secrets_filepath)
modify_file(secrets_filepath, "uc_client_id: ", value=line.rstrip())
elif cnt == 2:
print("Writing client secret to " + secrets_filepath)
modify_file(secrets_filepath, "uc_client_secret: ", value=line.rstrip())
line = fp.readline()
cnt += 1
def read_token_line(self):
token_path = 'app_usercred.txt'
with open(token_path) as fp:
line = fp.readline()
print("Writing access token to " + secrets_filepath)
modify_file(secrets_filepath, "uc_access_token: ", value=line.rstrip())
def read_config_line():
with open(config_filepath) as fp:
line = fp.readline()
modify_file(config_filepath, "mastodon_hostname: ", value=hostname)
modify_file(config_filepath, "bot_username: ", value=bot_username)
def read_lang_config_line():
with open(lang_config_filepath) as fp:
line = fp.readline()
lang = input("Enter Bot lang, ex. en or ca: ")
modify_file(lang_config_filepath, "bot_lang: ", value=lang)
def log_in():
error = 0
try:
global hostname, bot_username
hostname = input("Enter Mastodon hostname: ")
user = input("User name, ex. user@" + hostname +"? ")
user_password = getpass.getpass("User password? ")
bot_username = input("Bot's username, ex. mastochess: ")
app_name = input("This app name? ")
Mastodon.create_app(app_name, scopes=["read","write"],
to_file="app_clientcred.txt", api_base_url=hostname)
mastodon = Mastodon(client_id = "app_clientcred.txt", api_base_url = hostname)
mastodon.log_in(
user,
user_password,
scopes = ["read", "write"],
to_file = "app_usercred.txt"
)
except MastodonIllegalArgumentError as i_error:
error = 1
if os.path.exists("secrets/secrets.txt"):
print("Removing secrets/secrets.txt file..")
os.remove("secrets/secrets.txt")
if os.path.exists("app_clientcred.txt"):
print("Removing app_clientcred.txt file..")
os.remove("app_clientcred.txt")
sys.exit(i_error)
except MastodonNetworkError as n_error:
error = 1
if os.path.exists("secrets/secrets.txt"):
print("Removing secrets/secrets.txt file..")
os.remove("secrets/secrets.txt")
if os.path.exists("app_clientcred.txt"):
print("Removing app_clientcred.txt file..")
os.remove("app_clientcred.txt")
sys.exit(n_error)
except MastodonReadTimeout as r_error:
error = 1
if os.path.exists("secrets/secrets.txt"):
print("Removing secrets/secrets.txt file..")
os.remove("secrets/secrets.txt")
if os.path.exists("app_clientcred.txt"):
print("Removing app_clientcred.txt file..")
os.remove("app_clientcred.txt")
sys.exit(r_error)
except MastodonAPIError as a_error:
error = 1
if os.path.exists("secrets/secrets.txt"):
print("Removing secrets/secrets.txt file..")
os.remove("secrets/secrets.txt")
if os.path.exists("app_clientcred.txt"):
print("Removing app_clientcred.txt file..")
os.remove("app_clientcred.txt")
sys.exit(a_error)
finally:
if error == 0:
create_dir()
create_file()
write_params()
client_path = 'app_clientcred.txt'
read_client_lines(client_path)
token_path = 'app_usercred.txt'
read_token_line(token_path)
if os.path.exists("app_clientcred.txt"):
print("Removing app_clientcred.txt temp file..")
os.remove("app_clientcred.txt")
if os.path.exists("app_usercred.txt"):
print("Removing app_usercred.txt temp file..")
os.remove("app_usercred.txt")
print("Secrets setup done!\n")
def modify_file(file_name,pattern,value=""):
fh=fileinput.input(file_name,inplace=True)
for line in fh:
replacement=pattern + value
line=re.sub(pattern,replacement,line)
sys.stdout.write(line)
fh.close()
# Returns the parameter from the specified file
def get_parameter( parameter, file_path ):
# Check if secrets file exists
if not os.path.isfile(file_path):
print("File %s not found, creating it."%file_path)
log_in()
# Find parameter in file
with open( file_path ) as f:
for line in f:
if line.startswith( parameter ):
return line.replace(parameter + ":", "").strip()
# Cannot find parameter, exit
print(file_path + " Missing parameter %s "%parameter)
sys.exit(0)
# Returns the parameter from the specified file
def get_hostname( parameter, config_filepath ):
# Check if secrets file exists
if not os.path.isfile(config_filepath):
print("File %s not found, creating it."%config_filepath)
create_config()
# Find parameter in file
with open( config_filepath ) as f:
for line in f:
if line.startswith( parameter ):
return line.replace(parameter + ":", "").strip()
# Cannot find parameter, exit
print(config_filepath + " Missing parameter %s "%parameter)
write_config()
read_config_line()
print("setup done!")
sys.exit(0)
# Returns the parameter from the specified file
def get_lang( parameter, lang_config_filepath ):
# Check if lang file exists
if not os.path.isfile(lang_config_filepath):
print("File %s not found, creating it."%lang_config_filepath)
create_lang_config()
# Find parameter in file
with open( lang_config_filepath ) as f:
for line in f:
if line.startswith( parameter ):
return line.replace(parameter + ":", "").strip()
# Cannot find parameter, exit
print(lang_config_filepath + " Missing parameter %s "%parameter)
write_lang_config()
read_lang_config_line()
print("Bot lang setup done!")
sys.exit(0)
###############################################################################
# main
if __name__ == '__main__':
# Load secrets from secrets file
secrets_filepath = "secrets/secrets.txt"
uc_client_id = get_parameter("uc_client_id", secrets_filepath)
uc_client_secret = get_parameter("uc_client_secret", secrets_filepath)
uc_access_token = get_parameter("uc_access_token", secrets_filepath)
# Load configuration from config file
config_filepath = "config/config.txt"
mastodon_hostname = get_hostname("mastodon_hostname", config_filepath)
bot_username = get_parameter("bot_username", config_filepath)
# Load Bot lang from config file
lang_config_filepath = "config/lang_config.txt"
bot_lang = get_lang("bot_lang", lang_config_filepath) # E.g., en or ca