Ejemplo n.º 1
0
 def __init__(self, user_database):
     self.user_database = user_database
     self._clients = set()
     self.last_message_sender = ''
     self.user_list = []
     self.fernet = Fernet(FERNET_KEY)
     self.command_handler = CommandHandler(user_database, self.fernet)
Ejemplo n.º 2
0
 def test_help(self):
     handler = CommandHandler()
     room = Chatroom("../config/test_config/chat.yaml")
     socket = Mwsc()
     user = User(socket, "Test")
     test_helper.sync(handler.handle_command("!help", user, room))
     self.assertTrue("!help" in user.websocket.incoming[-1])
    def __init__(self, plugin, window):
        self.window = window
        self.plugin = plugin
        self.command_handler = CommandHandler()

        self.set_status()

        for view in window.get_views():
            self.connect_handlers(view)

        window.connect('tab_added', self.on_tab_added)
Ejemplo n.º 4
0
    def test_is_command(self):
        handler = CommandHandler()

        valid = ["!valid", "!help", "!valid with args"]
        invalid = ["message", "message 2", "message!", "!", "message !three"]

        for s in valid:
            self.assertTrue(handler.is_command(s))

        for s in invalid:
            self.assertFalse(handler.is_command(s))
Ejemplo n.º 5
0
    def __init__(self, chat_config_path):
        """
        Create a new Chatroom

        Args:
            chat_config_path (str): path to chat config yaml
        """

        # Dict[Websocket, User]
        self.connected = dict()
        self.command_handler = CommandHandler()
        self.config = ConfigManager(chat_config_path)
        self.name_generator = AdjAnimalNameGenerator(
            self.config["name_generator"]["adjective_path"],
            self.config["name_generator"]["animal_path"])
        self.env = self.config["meta"]["enviornment"]
def run_simulation():
    my_sim = FlightSimulator()
    my_commander = CommandHandler(command_poster_fn=my_sim.post_command)
    my_sim.set_commander(my_commander)

    my_commander.initialize_sdk()
    my_commander.take_off()
    my_commander.right(20)
    my_commander.rotate_clockwise(15)
    my_commander.land()
    my_commander.take_off()
    my_commander.rotate_clockwise(15)

    print('\n\n\ntracing route back...\n\n\n')
    my_commander.track_back()
    print('flight logs saved to logs')
Ejemplo n.º 7
0
 def __response(self, line, client):
     """
     Manages incoming lines
     """
     parser = Parser()
     response = ""
     if not parser.parse(line):
         response = f"Command corrupted: {line}"
     else:
         handler = CommandHandler(self.__root_directory)
         instruction = parser.instruction(line)
         if instruction == "up":
             response = self.__receive_file(client, handler)
         elif instruction == "down":
             response = self.__send_file(line, client, handler)
         else:
             response = handler.execute(line)
     return response
Ejemplo n.º 8
0
    def run(self):
        self.log = logger_config.instance
        cache.log = self.log
        try:
            with open(config.DB_FILENAME, 'rb') as fp:
                self.db = pickle.load(fp)
        except:
            self.log.error("error loading db, defaulting to empty db")
            self.db = {}
        self.api = TgApi(self.log)
        self.repository = MarketRepository(self.log)
        self.command_handler = CommandHandler(self.api, self.repository,
                                              self.db, self.log)

        self.log.debug("db at start: {}".format(self.db))
        self.last_update = self.db[
            'last_update'] if 'last_update' in self.db else 0
        # main loop
        loop = True
        while loop:
            try:
                updates = self.api.getUpdates(self.last_update)
                if updates is None:
                    self.log.error('get update request failed')
                else:
                    self.processUpdates(updates)
                try:
                    self.processAlerts()
                except:
                    self.log.exception("exception at processing alerts")
                time.sleep(1)
            except KeyboardInterrupt:
                self.log.info("interrupt received, stopping…")
                loop = False
            except:
                self.log.exception("exception at processing updates")
                loop = False

            self.persist_db()
            cache.persist()
Ejemplo n.º 9
0
    def __init__(
        self,
        config: Config,
        store: Storage,
        github: Github,
        repo: Repository,
    ):
        self.config = config
        self.github = github
        self.repo = repo
        self.command_handler = CommandHandler(config, store, repo)

        # Start a flash webserver
        self.app = Flask(__name__)

        webhook = Webhook(
            self.app,
            endpoint=self.config.webhook_path,
            secret=self.config.webhook_secret,
        )

        @self.app.route("/")
        def hello_world():
            return "Hello, world!"

        @webhook.hook("issue_comment")
        def on_issue_comment(data):
            log.debug(
                f"Got comment: {json.dumps(data, indent=4, sort_keys=True)}")
            self._process_comment(data)

        @webhook.hook("pull_request_review_comment")
        def on_pull_request_review_comment(data):
            log.debug(
                f"Got PR review comment: {json.dumps(data, indent=4, sort_keys=True)}"
            )
            self._process_comment(data)
Ejemplo n.º 10
0
# -*- coding: utf-8 -*-
from command_handler import CommandHandler
import thread
import time

com = CommandHandler()
while com.handle():
    time.sleep(0.5)
Ejemplo n.º 11
0
import telebot
from command_handler import CommandHandler
from users_repository import UsersRepository
from states import State
from users_repository import UserInfo
from requests.exceptions import ReadTimeout
import time
import os
import requests
from bs4 import BeautifulSoup
API_TOKEN = '1391169462:AAG3l2DwCxs1Cys4kqh3L2cG32Od7ryb1ZY'

bot = telebot.TeleBot(API_TOKEN)
users = UsersRepository("users")

handler = CommandHandler(bot, users)


@bot.message_handler(commands=['help', 'start'])
def send_welcome(message):
    user_id = message.from_user.id
    bot.send_message(
        message.chat.id,
        "Привет. Напиши запрос чтобы узнать курс валют на сегодня. Пример : Курс доллара в Москве"
    )
    if not users.exists(user_id):
        user_info = UserInfo(user_id, state=State.MAIN)
        users.save(user_info)
        #handler.keyboard_in_tournaments(message)
    #else:
    #handler.keyboard_in_tournaments(message)
Ejemplo n.º 12
0
 def __init__(self):
     self.command_handler = CommandHandler()
Ejemplo n.º 13
0
import logging
from aiogram import Bot, Dispatcher, executor, types

import config
from command_handler import CommandHandler
from constants import CAPTCHA_SUCCESS
from new_members_handler import NewMembersHandler
from text_handler import TextHandler

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

bot = Bot(token=config.ACCESS_TOKEN, )
dp = Dispatcher(bot=bot, )
textHandler = TextHandler()
commandHandler = CommandHandler()
newMembersHandler = NewMembersHandler(bot)


@dp.message_handler(content_types=types.ContentType.NEW_CHAT_MEMBERS)
async def process_new_member(message: types.Message):
    await newMembersHandler.handle(message)


@dp.callback_query_handler(lambda callback: True)
async def process_callback(callback: types.CallbackQuery):
    if callback.message:
        if callback.data == CAPTCHA_SUCCESS:
            await newMembersHandler.handleCaptchaCallback(callback)

Ejemplo n.º 14
0
#Connect to users database
dbedit.setup()

#Get the list of folders and add to sys.path
for root, dirs, files in os.walk(r'.'):
    for dir in dirs[:3]:
        sys.path.append(os.path.realpath(f'{root}/{dir}'))

config = configparser.ConfigParser()
config.read('data/config.ini', encoding='utf-8')

#Create a discord client
client = discord.Client()
#Create handlers
handler = CommandHandler(client, config)
reactionHandler = ReactionHandler(client, config)
#Register all commands
handler.register_commands_in_dir('./commands')


@client.event
async def on_ready():
    print("Logged in as: " + str(client.user.name))


@client.event
async def on_reaction_add(reaction, user):
    #Pass reaction to handler
    await reactionHandler.handle(reaction, user)
Ejemplo n.º 15
0
import discord
import diy_parser
from command_handler import CommandHandler
import os

token = os.environ['TOKEN']
color = 16098851

client = discord.Client()
diy_list = diy_parser.get_diy_masterlist()
ch = CommandHandler(client)


# Not entirely sure what this method does but it was in the tutorial and I'm afraid to remove it
@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))


# Method for sending message when author message starts with !diy
@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('!ribbot'):
        await ch.command_handler(message)


# ====================
# describe diy
Ejemplo n.º 16
0
def main():
    ch = CommandHandler()
    while True:
        result = ch.handle_command(input('>>>'))
        if result:
            print(result)
Ejemplo n.º 17
0
#!/usr/bin/python3
import sys

from fachwoerter_bot import FachwoerterBot
from command_handler import CommandHandler

if __name__ == '__main__':
    bot = FachwoerterBot()

    if '--tweet' in sys.argv:
        word = bot.get_fachwort(bot.cursor)
        bot.tweet(word)
        quit()

    print('Fachwörter Bot v0.1')

    command_handler = CommandHandler(bot)

    while True:
        command_input = input('> ').lower()
        command_parts = command_input.split(' ')
        command = command_parts[0]
        args = command_parts[1:]

        command_handler.handle_command(command, args)
Ejemplo n.º 18
0
 def handle_cmd(self, data):
     CommandHandler().exec_cmd(self.transport, data)
Ejemplo n.º 19
0
 def test_help_registered(self):
     handler = CommandHandler()
     self.assertIn("!help", handler.registered_commands)
Ejemplo n.º 20
0
    parser.add_argument(
        '-z',
        '--zabbix',
        default=False,
        action='store_true',
        help='Select whether to use zabbix as a health monitor or not.')
    parser.add_argument(
        '--log-level',
        action="store",
        type=str,
        choices=["critical", "error", "warning", "info", "debug", "notset"],
        default="info",
        help='Select the log level of the program.')
    parser.add_argument('--verbose',
                        default=False,
                        action='store_true',
                        help='Select whether to output logs to the console.')
    args = parser.parse_args()

    port = 5006
    handler = CommandHandler(args, port)
    server = ConnectionFactory(handler)

    try:
        server.run_server(port)
    except Exception as e:
        print str(e)
        raise e
    finally:
        server.handler.shutdown()
Ejemplo n.º 21
0
        # print output_list
        for output in output_list:
            # slack output should be parsed as a command
            if output and 'text' in output and AT_BOT in output['text']:
                return 'command'
            # slack output should be parsed by NLP engine
            if output and 'text' in output:
                return 'nlp'

    return None, None, None, None


if __name__ == "__main__":
    text_parser = EmojiParser(slack_client)

    command_handler = CommandHandler(slack_client)
    READ_WEBSOCKET_DELAY = 0.5  # 1 second delay between reading from data stream
    if slack_client.rtm_connect():
        print("ReactionAdder connected and running!")
        while True:
            output_list = slack_client.rtm_read()
            msg_type = determine_message_type(output_list)
            if msg_type == 'command':
                __message, channel = command_handler.get_command_info(
                    output_list)
                command_handler.parse_command(__message.split(), channel)
            elif msg_type == 'nlp':
                print("in nlp branch")
                emoji_list, channel, timestamp, user = text_parser.parse_message(
                    output_list)
                print emoji_list
Ejemplo n.º 22
0
from command_handler import CommandHandler
import generators


if __name__ == '__main__':
    """
        核心的背单词的文件 只需要运行此文件即可
        y为认识此单词 n为不认识此单词 eof为退出
        error为rollback上一个单词入单词池
        excel需要提取的sheet在108行的sheets_set来指定 可以指定多个set
        在背诵过程中error过或n过的单词在程序正常结束后会被记入此文件的difficulties的sheet中
        需要人为创建这个名为difficulties的sheet或者自行指定一个名称
    """
    modules_name = list(map(lambda s: s.capitalize(), input("module_name:").split("_")))
    module = getattr(generators, f"{''.join(modules_name)}Generator")
    wordsDb = module.init_all_words()
    handler = CommandHandler(wordsDb)
    handler.loop()