Esempio n. 1
0
def check_steam_dir():
    if get_config('steam_path') == 'reg' and os.path.isfile(
            fetch_reg('SteamPath') + '\\Steam.exe'):
        return True
    elif os.path.isfile(get_config('steam_path') + '\\Steam.exe'):
        return True
    else:
        return False
    def save(self):
        dump_dict = {
            'locale': get_config('locale'),
            'try_soft_shutdown': self.soft_shutdown,
            'autoexit': self.autoexit,
            'mode': self.mode,
            'show_avatar': self.avatar,
            'last_pos': get_config('last_pos'),
            'steam_path': get_config('steam_path'),
            'ui_mode': self.ui_mode
        }

        config_write_dict(dump_dict)
Esempio n. 3
0
    def __init__(self,
                 content,
                 feeling=2,
                 sign=0,
                 coupon=0,
                 at=True,
                 auto_image=True):

        self.config = get_config()
        self.auto_image = auto_image

        c_type = type(content)
        chain = []

        sp = [TextImage, Image, Voice, Text]
        if c_type is str:
            chain += self.__trans_str(content.strip('\n'))
        elif c_type is list:
            for item in content:
                if type(item) is str:
                    chain += self.__trans_str(item.strip('\n'))
                if type(item) in sp:
                    chain += item.item
        else:
            if c_type in sp:
                chain += content.item

        self.content = chain
        self.feeling = feeling
        self.coupon = coupon
        self.sign = sign
        self.at = at
Esempio n. 4
0
def open_screenshot(steamid64, steam_path=get_config('steam_path')):
    if steam_path == 'reg':
        steam_path = fetch_reg('steampath')

    if '/' in steam_path:
        steam_path = steam_path.replace('/', '\\')

    os.startfile(
        f'{steam_path}\\userdata\\{steam64_to_32(steamid64)}\\760\\remote')
Esempio n. 5
0
    def __init__(self, session, handler=None):
        server = get_config('server')

        host = server['server_ip']
        port = server['server_port']
        super().__init__('ws://%s:%d/all?sessionKey=%s' %
                         (host, port, session))
        self.connect()
        self.handler = handler
Esempio n. 6
0
def loginusers():
    '''
    Fetch loginusers.vdf and return SteamID64, AccountName,
    PersonaName values as lists.
    :param steam_path: Steam installation path override
    '''
    if get_config('steam_path') == 'reg':
        steam_path = fetch_reg('steampath')
    else:
        steam_path = get_config('steam_path')

    if '/' in steam_path:
        steam_path = steam_path.replace('/', '\\')

    vdf_file = os.path.join(steam_path, 'config', 'loginusers.vdf')

    try:
        with open(vdf_file, 'r', encoding='utf-8') as vdf_file:
            vdf = vdf_file.read().splitlines()
    except FileNotFoundError:
        return [], [], []

    steam64_list = []
    account_name = []
    persona_name = []

    rep = {"\t": "", '"': ""}
    rep = dict((re.escape(k), v) for k, v in rep.items())
    pattern = re.compile("|".join(rep.keys()))

    for i, v in enumerate(vdf):
        if v == "\t{":
            steam64 = pattern.sub(lambda m: rep[re.escape(m.group(0))],
                                  vdf[i - 1])
            account = pattern.sub(lambda m: rep[re.escape(m.group(0))],
                                  vdf[i + 1])
            persona = pattern.sub(lambda m: rep[re.escape(m.group(0))],
                                  vdf[i + 2])
            steam64_list.append(steam64)
            account_name.append(account.replace("AccountName", ""))
            persona_name.append(persona.replace("PersonaName", ""))
    return steam64_list, account_name, persona_name
Esempio n. 7
0
def get_color(key):
    theme = get_config('theme')
    try:
        if theme == 'light':
            return COLOR_LIGHT[key]
        elif theme == 'dark':
            return COLOR_DARK[key]

    except KeyError:
        print('WARNING: get_color was called with wrong color key', key)
        return 'black'
Esempio n. 8
0
    def __init__(self):
        config = get_config('database')

        self.comb = Mysql(config)

        self.user = User(self.comb)
        self.group = Group(self.comb)
        self.config = Config(self.comb)
        self.remind = Remind(self.comb)
        self.message = Message(self.comb)
        self.material = Material(self.comb)
        self.operator = Operator(self.comb)
        self.function = Function(self.comb)
        self.resource = Resource(self.comb)
Esempio n. 9
0
def initialize():
    """connect to couchDB"""
    try:
        database.server = Server(database_url)
        server.version_info()
        print("Connected to database-server " + str(database.server))
        for database_name in database_names:
            try:
                server[database_name]
            except Exception as e:
                try:
                    server.create(database_name)
                except Exception as e:
                    print("Could not create database " + database_name + ": " +
                          str(e))
        # check if master_user exists, else create document
        try:
            server[USER_DB_NAME][config.get_config()["master_username"]]
        except Exception as e:
            setup(config.get_config()["master_username"],
                  config.get_config()["master_password"])

    except Exception as e:
        print("Could not connect to database-server: " + str(e))
Esempio n. 10
0
def test():
    print('Listing current config...')
    print('locale:', get_config('locale'))
    print('autoexit:', get_config('autoexit'))
    print('mode:', get_config('mode'))
    print('try_soft_shutdown:', get_config('try_soft_shutdown'))
    print('show_avatar:', get_config('show_avatar'))
    print('steam_path:', get_config('steam_path'))

    print('Checking registry...')
    for key in ('AutoLoginUser', 'RememberPassword', 'SteamExe', 'SteamPath',
                'pid', 'ActiveUser'):
        print(f'{key}:', fetch_reg(key))

    print('Checking Steam.exe location...')
    if check_steam_dir() and get_config('steam_path') == 'reg':
        print('Steam located at', fetch_reg('steampath'))
    elif check_steam_dir():
        print('Steam located at', get_config('steam_path'), '(Manually set)')
    else:
        print('Steam directory invalid')
        return False
    return True
Esempio n. 11
0
import time
import datetime

from database.baseController import BaseController
from modules.commonMethods import Reply, word_in_sentence, calc_time_total
from modules.config import get_config

admin_id = get_config('admin_id')
database = BaseController()


def group_admin(data):
    permission = data['permission']
    group_id = data['group_id']
    user_id = data['user_id']
    message = data['text']

    if permission in ['OWNER', 'ADMINISTRATOR'] or user_id == admin_id:

        if word_in_sentence(message, ['休息', '下班']):
            res = database.group.get_status(group_id)
            if not res or res['active'] == 1:
                database.group.set_status(group_id, 0, int(time.time()))
                return Reply('阿米娅打卡下班啦,博士需要阿米娅的时候再让阿米娅工作吧。^_^')

        if word_in_sentence(message, ['工作', '上班']):
            res = database.group.get_status(group_id)
            if res and res['active'] == 0:
                seconds = int(time.time()) - int(res['sleep_time'])
                total = calc_time_total(seconds)
                text = '打卡上班啦~阿米娅%s休息了%s……' % ('才' if seconds < 600 else '一共', total)
Esempio n. 12
0
import re
import os
import shutil
import datetime

from PIL import Image, ImageDraw, ImageFont
from modules.config import get_config

resource = 'resource/message'
font_file = 'resource/style/AdobeHeitiStd-Regular.otf'
logo_file = 'resource/style/rabbit.png'
logo_file_white = 'resource/style/rabbit-white.png'

# 配置 mirai-api-http 的缓存路径可以顺手清理其缓存的图片
console_temp = get_config('message.console_temp_images')


def cut_code(code, length):
    code_list = re.findall('.{' + str(length) + '}', code)
    code_list.append(code[(len(code_list) * length):])
    res_list = []
    for n in code_list:
        if n != '':
            res_list.append(n)
    return res_list


def split_text(text):
    text = text.strip('\n').split('\n')

    new_text = []
Esempio n. 13
0
import winreg
import gettext
from modules.errormsg import error_msg
from modules.config import get_config

LOCALE = get_config('locale')

t = gettext.translation('steamswitcher',
                        localedir='locale',
                        languages=[LOCALE],
                        fallback=True)
_ = t.gettext


HKCU = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)


def fetch_reg(key):
    '''Return given key's value from steam registry path.'''

    if key in ('pid', 'ActiveUser'):
        reg_path = r"Software\Valve\Steam\ActiveProcess"
    else:
        reg_path = r"Software\Valve\Steam"

    try:
        reg_key = winreg.OpenKey(HKCU, reg_path)
        value_buffer = winreg.QueryValueEx(reg_key, key)
        value = value_buffer[0]
        winreg.CloseKey(reg_key)
    except OSError:
Esempio n. 14
0
    def __init__(self,
                 master,
                 username,
                 profilename,
                 command=None,
                 rightcommand=None,
                 image='default'):
        self.update_color(init=True)

        self.master = master
        self.frame = tk.Frame(master, borderwidth=3, width=84, height=100)
        self.command = command
        self.frame.config(background=self.normal, cursor='hand2')
        self.frame.pack_propagate(0)

        self.frame.bind('<Button-1>', lambda event: self.__click())
        self.frame.bind('<ButtonRelease-1>',
                        lambda event: self.__release(event))
        self.frame.bind('<Button-3>', rightcommand)
        self.frame.bind('<Enter>', lambda event: self.__enter())
        self.frame.bind('<Leave>', lambda event: self.__leave())

        self.onbutton = False
        self.is_clicked = False
        self.enabled = True
        self.avatar = None
        size = 48

        if get_config('show_avatar') == 'true':
            self.avatar = tk.Canvas(self.frame,
                                    width=size,
                                    height=size,
                                    bd=0,
                                    highlightthickness=0)

            try:
                if image != 'default':
                    img = Image.open(f"avatar/{image}.jpg").resize(
                        (size, size))
                else:
                    raise FileNotFoundError

            except FileNotFoundError:
                img = Image.open("asset/default.jpg").resize((size, size))

            self.imgtk = ImageTk.PhotoImage(img)
            self.avatar.create_image(size // 2, size // 2, image=self.imgtk)
            self.avatar.pack(side='top', pady=(2, 0))

            self.avatar.bind('<Button-1>', lambda event: self.__click())
            self.avatar.bind('<ButtonRelease-1>',
                             lambda event: self.__release(event))
            self.avatar.bind('<Button-3>', rightcommand)

        self.acc_label = ttk.Label(self.frame)
        self.acc_label.config(background=self.normal, foreground=self.text)
        self.acc_label.pack(side='top', pady=(2, 0))
        self.acc_label.bind('<Button-1>', lambda event: self.__click())
        self.acc_label.bind('<ButtonRelease-1>',
                            lambda event: self.__release(event))
        self.acc_label.bind('<Button-3>', rightcommand)

        if tkfont.Font(font=self.acc_label['font']).measure(username) > 86:
            while tkfont.Font(
                    font=self.acc_label['font']).measure(username) > 86:
                username = username[:-1]
            else:
                username = f'{username}..'

        self.acc_label.configure(text=username)

        self.profile_label = ttk.Label(self.frame)
        self.profile_label.config(background=self.normal, foreground=self.text)
        self.profile_label.pack(side='top')
        self.profile_label.bind('<Button-1>', lambda event: self.__click())
        self.profile_label.bind('<ButtonRelease-1>',
                                lambda event: self.__release(event))
        self.profile_label.bind('<Button-3>', rightcommand)

        if tkfont.Font(
                font=self.profile_label['font']).measure(profilename) > 86:
            while tkfont.Font(
                    font=self.profile_label['font']).measure(profilename) > 86:
                profilename = profilename[:-1]
            else:
                profilename = f'{profilename}..'

        self.profile_label.configure(text=profilename)
Esempio n. 15
0
def main(launch_str=""):

    _define_log(launch_str)

    # Init order MATTERS

    log.info("Starting init...")

    # Get data from the config file
    cfg.get_config(launch_str)

    # Set up intents
    intents = Intents.none()
    intents.guilds = True
    intents.members = True
    intents.bans = False
    intents.emojis = False
    intents.integrations = False
    intents.webhooks = False
    intents.invites = False
    intents.voice_states = False
    intents.presences = True
    intents.messages = True
    # intents.guild_messages Activated by the previous one
    # intents.dm_messages Activated by the previous one
    intents.reactions = False
    # intents.guild_reactions
    # intents.dm_reactions
    intents.typing = False
    intents.guild_typing = False
    intents.dm_typing = False
    client = commands.Bot(command_prefix=cfg.general["command_prefix"],
                          intents=intents)

    # Remove default help
    client.remove_command('help')

    # Initialise db and get all the registered users and all bases from it
    modules.database.init(cfg.database)
    modules.database.get_all_elements(Player.new_from_data, "users")
    modules.database.get_all_elements(Base, "static_bases")
    modules.database.get_all_elements(Weapon, "static_weapons")

    # Get Account sheet from drive
    modules.accounts_handler.init(cfg.GAPI_JSON)

    # Establish connection with Jaeger Calendar
    modules.jaeger_calendar.init(cfg.GAPI_JSON)

    # Initialise display module
    ContextWrapper.init(client)

    # Init lobby
    modules.lobby.init(Match, client)

    # Init stat processor
    modules.stat_processor.init()

    # Add init handlers
    _add_init_handlers(client)

    if launch_str == "_test":
        _test(client)

    # Add all cogs
    modules.loader.init(client)

    # Run server
    client.run(cfg.general["token"])
Esempio n. 16
0
    def __init__(self,
                 master,
                 username,
                 profilename,
                 command=None,
                 rightcommand=None,
                 image='default'):
        self.update_color(init=True)

        self.master = master
        self.frame = tk.Frame(master, borderwidth=3)
        self.command = command
        self.frame.config(background=self.normal, cursor='hand2')

        self.frame.bind('<Button-1>', lambda event: self.__click())
        self.frame.bind('<ButtonRelease-1>',
                        lambda event: self.__release(event))
        self.frame.bind('<Button-3>', rightcommand)
        self.frame.bind('<Enter>', lambda event: self.__enter())
        self.frame.bind('<Leave>', lambda event: self.__leave())

        self.is_clicked = False
        self.enabled = True
        self.avatar = None

        username_font = tkfont.Font(weight=tkfont.BOLD,
                                    size=12,
                                    family='Arial')

        if get_config('show_avatar') == 'true':
            self.avatar = tk.Canvas(self.frame,
                                    width=40,
                                    height=40,
                                    bd=0,
                                    highlightthickness=0)

            try:
                if image != 'default':
                    img = Image.open(f"avatar/{image}.jpg").resize((40, 40))
                else:
                    raise FileNotFoundError

            except FileNotFoundError:
                img = Image.open("asset/default.jpg").resize((40, 40))

            self.imgtk = ImageTk.PhotoImage(img)
            self.avatar.create_image(20, 20, image=self.imgtk)
            self.avatar.pack(side='left', padx=(1, 3), pady=0)

            self.avatar.bind('<Button-1>', lambda event: self.__click())
            self.avatar.bind('<ButtonRelease-1>',
                             lambda event: self.__release(event))
            self.avatar.bind('<Button-3>', rightcommand)

        self.acc_label = ttk.Label(self.frame,
                                   text=username,
                                   font=username_font)
        self.acc_label.config(background=self.normal, foreground=self.text)
        self.acc_label.pack(anchor='w', padx=(3, 0))
        self.acc_label.bind('<Button-1>', lambda event: self.__click())
        self.acc_label.bind('<ButtonRelease-1>',
                            lambda event: self.__release(event))
        self.acc_label.bind('<Button-3>', rightcommand)

        self.profile_label = ttk.Label(self.frame, text=profilename)
        self.profile_label.config(background=self.normal, foreground=self.text)
        self.profile_label.pack(anchor='w', padx=(3, 0))
        self.profile_label.bind('<Button-1>', lambda event: self.__click())
        self.profile_label.bind('<ButtonRelease-1>',
                                lambda event: self.__release(event))
        self.profile_label.bind('<Button-3>', rightcommand)
Esempio n. 17
0
import argparse
from pathlib import Path

from modules import log
from modules import utils
from modules import config


config = config.get_config('config')
log_path = Path(config['global']['log_path'])

script_name = utils.get_script_name(__file__)
logger = log.get_logger(script_name, log_path=log_path)


def main(args):
  print('this is a template')


def get_parser():
  parser = argparse.ArgumentParser(
      description='Template script description',
      formatter_class=argparse.ArgumentDefaultsHelpFormatter
  )
  parser.add_argument(
      '-t',
      '--test',
      action='store_true',
      help='Test run. No files will be modified'
  )
  return parser
Esempio n. 18
0
import sys, os, logging

application = Flask("steam-language-filter")

logging.basicConfig()
log = logging.getLogger('web_api')
log.setLevel(logging.INFO)
fh = logging.FileHandler('web_api.log')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
log.addHandler(fh)

config_filename = "web_api.config"
config_path = "{0}/{1}".format(os.path.dirname(os.path.realpath(__file__)),
                               config_filename)

default_db_filename = "web_api.sql"
db_path = "{0}/{1}".format(os.path.dirname(os.path.realpath(__file__)),
                           default_db_filename)

default_log_level = "DEBUG"

config = get_config(config_path, db_path, default_log_level)

log.setLevel(config['log_level'])
db = Database(application, config['db_filepath'])

if __name__ == "__main__":
    application.run(host='0.0.0.0', debug=True)
Esempio n. 19
0
import os
import json
import requests

from database.baseController import BaseController
from modules.config import get_config

database = BaseController()

config = get_config()
self_id = str(config['self_id'])
admin_id = str(config['admin_id'])
session_file = 'temp/session.txt'


class HttpRequests:
    def __init__(self):
        self.request = requests.session()
        self.config = config

    def url(self, interface):
        # http://miraiHost:miraiPost/API
        # 生成向mirai的端口请求的url
        return 'http://%s:%d/%s' % (self.config['server']['server_ip'],
                                    self.config['server']['server_port'],
                                    interface)

    def post(self, interface, data):

        response = self.request.post(
            self.url(interface),
Esempio n. 20
0
import os
import sys
import gettext
import colour
import json
from PIL import Image, ImageTk
from modules.config import get_config, config_write_value, config_write_dict
from ruamel.yaml import YAML
from modules.util import check_steam_dir, create_shortcut
from modules.steamid import steam64_to_3, steam64_to_32, steam64_to_2

yaml = YAML()

t = gettext.translation('steamswitcher',
                        localedir='locale',
                        languages=[get_config('locale')],
                        fallback=True)
_ = t.gettext

with open('theme.json') as theme_json:
    theme_dict = json.loads(theme_json.read())
    COLOR_LIGHT = theme_dict['light']
    COLOR_DARK = theme_dict['dark']


def get_color(key):
    theme = get_config('theme')
    try:
        if theme == 'light':
            return COLOR_LIGHT[key]
        elif theme == 'dark':
Esempio n. 21
0
import os

# Internal imports
import modules.config as cfg
from modules.database import force_update, init as db_init, get_all_elements
import classes
import pathlib

# Find if we are in test mode or in production
if os.path.isfile(f"{pathlib.Path(__file__).parent.absolute()}/test"):
    LAUNCHSTR = "_test"
else:
    LAUNCHSTR = ""

# Init config file and database, get all weapons currently in db
cfg.get_config(LAUNCHSTR)
db_init(cfg.database)
get_all_elements(classes.Weapon, "static_weapons")

item_type_id = 26  # weapon

# List of all categories
we_cats = {
    2: 'Knife',  # DET
    3: 'Pistol',  # DET
    8: 'Carbine',  # DET
    7: 'Assault Rifle',  # DET
    139: 'Infantry Abilities',  # BAN
    4: 'Shotgun',  # BAN
    6: 'LMG',  # DET
    13: 'Rocket Launcher',  # NP, DET
Esempio n. 22
0
from modules.commonMethods import Reply
import random
from modules.config import get_config

config: dict = get_config()


def repeat(data):
    message = data['text']

    if random.random() < config.get("repeat_probability", 0):
        return Reply(message, at=False)
    else:
        return None