async def reload(self, msg: Message): # user check if not msg.author.id == utils.enderzombi(): await msg.channel.send('only ENDERZOMBI102 can do that') return module: str = msg.content.replace('reload', '', 1).strip() if not len( module ) > 0: if self.lastReload is None: await msg.channel.send('missing parameter') return else: module = self.lastReload self.lastReload = module await msg.channel.send(f'reloading module "{module}"') if module in self.module.modules.keys(): try: await self.module.reload(module) except Exception as e: await msg.channel.send( embed=utils.getTracebackEmbed(e) ) raise e else: await msg.channel.send(f'custom module "{module}" reloaded') else: if module == 'modules': try: importlib.reload( modules ) except Exception as e: await msg.channel.send( embed=utils.getTracebackEmbed(e) ) return else: self.module = modules.Modules() self.module.bot = self elif module == 'commands': try: importlib.reload(commands) except Exception as e: await msg.channel.send( embed=utils.getTracebackEmbed(e) ) return else: self.stdCommands = commands.Commands() self.stdCommands._bot = self elif module == 'utils': try: importlib.reload(utils) except Exception as e: await msg.channel.send( e ) return else: self.stdCommands = commands.Commands() self.stdCommands._bot = self else: await utils.send(msg, 'invalid module "{module}"') return await msg.channel.send(f'bot module "{module}" reloaded')
def check_update(self, update: Optional[str], mode=Optional[str]) -> None: if update == None or mode == None: return if mode == "load": logger.info(f"Loading {update}") if update == "commands": basic_commands = utils.load_json(self.config_dir / "basic_commands.json") global commands commands = reload(commands) self.commands = commands.Commands(self) elif update == "users": self.users = utils.load_json(self.config_dir / "users.json") elif update == "monitored_posts": self.monitored_posts = utils.load_json(self.config_dir / "monitored_posts.json") elif update == "monitored_streams": self.monitored_streams = utils.load_json( self.config_dir / "monitored_streams.json") elif mode == "save": logger.info(f"Saving {update}") if update == "users": utils.save_json(self.config_dir / "users.json", self.users) elif update == "monitored_posts": utils.save_json(self.config_dir / "monitored_posts.json", self.monitored_posts) elif update == "monitored_streams": utils.save_json(self.config_dir / "monitored_streams.json", self.monitored_streams)
def init_connection(self): """Initialize variables that are local to a connection, (needed if the client automatically reconnect)""" self.ready_lock.acquire( False) # reacquire the ready-lock in case of reconnection self.connected = PYMUMBLE_CONN_STATE_NOT_CONNECTED self.control_socket = None self.media_socket = None # Not implemented - for UDP media self.bandwidth = PYMUMBLE_BANDWIDTH # reset the outgoing bandwidth to it's default before connectiong self.server_max_bandwidth = None self.udp_active = False self.users = users.Users( self, self.callbacks ) # contain the server's connected users informations self.channels = channels.Channels( self, self.callbacks) # contain the server's channels informations self.blobs = blobs.Blobs(self) # manage the blob objects self.sound_output = soundoutput.SoundOutput( self, PYMUMBLE_AUDIO_PER_PACKET, self.bandwidth) # manage the outgoing sounds self.commands = commands.Commands( ) # manage commands sent between the main and the mumble threads self.receive_buffer = "" # initialize the control connection input buffer
def __init__(self): self.cmds = commands.Commands() self.fc = forecast.Forecast() self.timestamps = { '**:00:00': 'full_hour', '**:30:00': 'forecast', '09:30:00': 'standup', '10:00:00': 'standup' }
def test_commands(): """Tests the commands module.""" cmds = commands.Commands() assert cmds.opening("kings pawn") == \ "**B00 King's Pawn**. Moves: `1. e4`. " \ "Board: <https://lichess.org/analysis/rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR_b_KQkq>" assert cmds.opening("king pawn nimzowitsch defense wheeler gambit") == \ cmds.execute("opening King's Pawn Game: Nimzowitsch Defense: Wheeler Gambit")
def deactivate(self, window): self._instances[window].deactivate() del self._instances[window] if len(self._instances) == 0: commands.Commands().stop() if self._path in sys.path: sys.path.remove(self._path)
def main(im_path): ''' ............................. Offset ayarlamak için : o Son konumu göstermek için : s Çıkış için : e ............................. ''' print(main.__doc__) print("! Lütfen Tarayıcınızı Açın") print( "# Scrolldown ve ScrollUp klasörlerinin güncel olduğundan emin olun.") print("> Scrollbar-Down Lokasyonu Tespit Edilecek.") m = mouse.Controller() cmd = commands.Commands() pos = None last_pos = None while True: if not pos: pos = cmd.find(im_path, sensitive=True, center=True) last_pos = pos time.sleep(2) continue set = input( "# Offset ayarı için [o/O], İlgili konumu kaydetmek için [s/S].\n->" ) temp_pos = list(pos) m.position = temp_pos if set.lower() == 'o': offset = input(">Lütfen offset'i girin (x,y)\n->") if '(' in offset and ')' in offset: offset = eval(offset) else: offset = f"({offset})" offset = eval(offset) temp_pos[0] += offset[0] temp_pos[1] += offset[1] print("# Mouse pozisyonu ayarlanıyor..") m.position = temp_pos last_pos = temp_pos elif set.lower() == 's': print(">>> Position:", last_pos) print("# Kaydedilecek") elif set.lower() == 'e': print("Çıkılıyor..") break else: print("! Bilinmeyen parametre", set)
def __init__(self, prefix, client, status='{}help'): self.prefix = prefix self.status = status.format(self.prefix) self.client = client if " " in self.prefix: self.self_destruct() self.Token = customToken.Token("db/token.txt") self.UI = ui.UI(discord.Embed, "db/ui.cfg") self.Poll = poll.Poll(self.UI, "db/polls.json") self.Commands = commands.Commands(self.client, self.Poll, self.UI)
async def on_message(message): global conf, data, client if message.author != client.user: if message.content.startswith(conf.prefix): text = message.content[conf.prefix_len:] if text.startswith("ping"): await message.channel.send("pong") # admin commands elif text.startswith("music") and message.author.id in conf.admins: if message.author.id in conf.admins: await music.music(message) elif text.startswith("is_adm"): if message.author.id in conf.admins: await message.channel.send("True") else: await message.channel.send("False") elif text.startswith( "add_admin") and message.author.id in conf.admins: for user in message.mentions: conf.add_admin(user.id) print(user.name + " is now admin: " + message.author) conf.save() elif text.startswith( "set_adm_chan") and message.author.id in conf.admins: print("adm channel set") data.cmd = commands.Commands(client, config, message.channel, IS_SPEED_MODE) msg_tmp = await data.cmd.channel.send("adm channel set") await message.delete() await msg_tmp.delete(delay=20) elif text.startswith( "set_sb_chan") and message.author.id in conf.admins: if data.cmd: print("sb channel set") await data.cmd.set_sb_chan(message.channel) else: msg_temp = await message.channel.send( "Set admin channel first.") await msg_temp.delete(delay=30) await message.delete() # end admin commands elif message.channel.type is discord.ChannelType.private: if data.cmd: await data.cmd.answer(message) else: await message.channel.send("The game is not open yet.")
def __init__(self): gedit.Plugin.__init__(self) self._instances = {} self._path = os.path.dirname(__file__) if not self._path in sys.path: sys.path.insert(0, self._path) commands.Commands().set_dirs([ os.path.expanduser('~/.gnome2/gedit/commander/modules'), os.path.join(self.get_data_dir(), 'modules') ])
def __init__(self, script_dir: Path, config_dir: Path, config): self.script_dir = script_dir self.config_dir = config_dir self.config = config self.secrets = utils.load_json(config_dir / "secrets.json") self.users = utils.load_json(self.config_dir / "users.json") self.basic_commands = utils.load_json(self.config_dir / "basic_commands.json") self.monitored_streams = utils.load_json(self.config_dir / "monitored_streams.json") self.monitored_posts = utils.load_json(self.config_dir / "monitored_posts.json") self.commands = commands.Commands(self) if self.config["announcements_webhook"]["hooks"]: self.webhook = discord_webhook.DiscordWebhook( url=self.config["announcements_webhook"]["hooks"]) else: self.webhook = None logger.debug("Starting chrome webdriver") self.webdriver = utils.launch_chrome(self.script_dir / "other" / "chromedriver") self.webdriver_connected = None logger.debug(f"Initializing praw") self.reddit = praw.Reddit( username=self.secrets["user_name"], password=self.secrets["user_password"], client_id=self.secrets["app_id"], client_secret=self.secrets["app_secret"], user_agent=self.secrets["user_agent"], ) self.bot_name = self.reddit.user.me().name self.monitored_redditor = self.reddit.redditor( self.config["monitored_redditor"]) self.monitored_subreddits = self.config["monitored_subreddits"] logger.debug(f"Adding submission/inbox streams") self.open_feed_streams = { self.monitored_redditor: self.monitored_redditor.stream.submissions(pause_after=0, skip_existing=True), self.reddit.inbox: self.reddit.inbox.stream(pause_after=0, skip_existing=True), } self.websockets_dict = {}
def __init__(self): ProtocolBase.__init__(self) print("Controllee init") self.config = {} self.setVariable(VAR_SCALE, VAR_SCALE_DEFAULT, False) self.setVariable(VAR_MONITOR, VAR_MONITOR_DEFAULT, False) self.setVariable(VAR_SHOULD_UPDATE_COMMANDS, VAR_SHOULD_UPDATE_COMMANDS_DEFAULT, False) self.printConfig() reactor.callLater(1, self.sendScreenshot) self.commands = commands.Commands(self.config) self.commands.start()
def main(): root = Tk() screen = gui.gui(root) root.geometry("700x600") commands.Commands(screen) voice = voiceRec(screen) data("goodreads_library_export.csv") root.resizable(width=False, height=False) p = Process(target=voice.main) p.start() p2 = Process(target=root.mainloop) p2.start() threading.Thread(target=voice.main()).start() threading.Thread(target=root.mainloop()).start()
def __init__(self): self.db = Database() self.command = commands.Commands() self.encrypt = Encrypt() self.auth = Authentication() self.commands = { "help": self.command.help, "new": self.command.new, "show": self.command.show, "save": self.command.save, "search": self.command.search, "delete": self.command.delete, "update": self.command.update_master_password, "security": self.command.security }
def main(): print(msg.log_init) cfg = utils.Utils() cfg.readConfig() db_ = database.db(cfg.dbhost, cfg.dbuser, cfg.dbpass, cfg.db) db_.connect() cmd = cmds.Commands(cfg, db_) # Telegram-bot initialization updater = Updater(token=cfg.token, workers=200, use_context=True) dp = updater.dispatcher # Command handlers dp.add_handler(CommandHandler('start', cmd.start)) dp.add_handler(CommandHandler('help', cmd.help)) dp.add_handler(CommandHandler('addcategory', cmd.rmAddDatabase, pass_args=True)) dp.add_handler(CommandHandler('rmcategory', cmd.rmAddDatabase, pass_args=True)) dp.add_handler(CommandHandler('addtopic', cmd.rmAddDatabase, pass_args=True)) dp.add_handler(CommandHandler('rmtopic', cmd.rmAddDatabase, pass_args=True)) dp.add_handler(CommandHandler('addresource', cmd.rmAddDatabase, pass_args=True)) dp.add_handler(CommandHandler('rmresource', cmd.rmAddDatabase, pass_args=True)) dp.add_handler(CommandHandler('showresources', cmd.showTable, pass_args=True)) dp.add_handler(CommandHandler('showtopics', cmd.showTable, pass_args=True)) dp.add_handler(CommandHandler('showcategories', cmd.showTable, pass_args=True)) # Message Handlers # Start doing things updater.start_polling() updater.idle()
async def main() -> None: async with aiohttp.ClientSession() as session: TASKS.append(asyncio.create_task(server.Server().main())) if 'commands' in CONFIG: import commands TASKS.append(asyncio.create_task(commands.Commands().main())) if 'goodgame' in CONFIG: import goodgame for channel in CONFIG['goodgame'].getlist('channels'): TASKS.append( asyncio.create_task( goodgame.GoodGame(channel).main(session))) if 'peka2tv' in CONFIG: import peka2tv for channel in CONFIG['peka2tv'].getlist('channels'): p = peka2tv.Peka2tv(channel) TASKS.append(asyncio.create_task(p.main(session))) TASKS.append(asyncio.create_task(p.send_heartbeat())) if 'twitch' in CONFIG: import twitch channels = CONFIG['twitch'].getlist('channels') for channel in channels: TASKS.append( asyncio.create_task(twitch.Twitch(channel).main(session))) if channels.index(channel) == 0: if CONFIG['twitch'].getboolean('is_follows'): TASKS.append( asyncio.create_task( twitch.get_channel_id(channel))) TASKS.append( asyncio.create_task( twitch.TwitchFollows(channel).main())) if CONFIG['twitch'].getboolean('is_stats'): TASKS.append( asyncio.create_task( twitch.TwitchStats(channel).main())) if 'wasd' in CONFIG: import wasd w = wasd.WASD(CONFIG['wasd'].getint('channel')) TASKS.append(asyncio.create_task(w.main(session))) TASKS.append(asyncio.create_task(w.send_heartbeat())) await asyncio.gather(*TASKS)
def __init__(self): # load saved data with open('./options', 'r') as file: data = bjson.load(file) self.prefix = data['bot']['prefix'] # init stuff indents = discord.Intents.all() indents.presences = False # noinspection PyArgumentList self.client = discord.Client( intents=indents ) self.client.event( self.on_ready ) self.client.event( self.on_message ) self.client.event( self.on_member_join ) self.client.event( self.on_member_leave ) self.client.event( self.on_member_update ) self.eventChannel = data['bot']['eventChannel'] self.module = modules.Modules() self.stdCommands = commands.Commands() Bot._instance = self
def __init__(self, stdscr, palette, db): #currently highlighted window #left window is 0, right is 1 self.cur = 0 #pointer to the ncurses stdscr self.stdscr = stdscr #music database self.db = db #all the colours and stuff self.palette = palette #flag to decide if we kill the ui self.die = False #currently playing playlist self.cur_pl = None #amount of time in between drawing in seconds #not really a frame time but w/e self.frame_time = 0.01667 #actual music player self.player = player.Player(config.DEFAULT_VOLUME, config.VOL_STEP) #the windows of the player self.leftwin, self.botwin, self.textwin = self.__init_windows() #handles typed commands self.commands = commands.Commands(self) #input queue and thread self.inp = inp.Input(self) #thread for updating everything visually threading.Thread(target=self.__info_print_loop, daemon=True).start()
# pip2 install simplejson global config config=conf.config() # global picture icons_url = config['icons_url'] # import json import urllib2 snomXML = SnomXML() # Hue-Helligkeit = 0-254: command = commands.Commands(config['brightness']) system = rapi_system.RaPi_System() # Weather from OpenWeatherMap : owm = pyowm.OWM(config['my_owm_api_key']) # GPIO Nummern: GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) ############################################################################### class WebServer(BaseHTTPServer.BaseHTTPRequestHandler): ''' Webserver Class '''
import typeid import commands import funcptr import features import exttypes tree = ET.parse(dirname(realpath(__file__)) + "/vk.xml") root = tree.getroot() types = typeid.Types(root) enum.parse_enums(root, types) apiconst = enum.parse_api_constants(root) struct.parse_impldbg(types) cmds = commands.Commands(root) features.require_feature(root, "VK_VERSION_1_0", types, cmds) features.require_feature(root, "VK_VERSION_1_1", types, cmds) exceptext = [] extnames = typeid.Type("EXTENSION_NAMES", "enum", enum.En("", []), []) for ext in root.findall("./extensions/extension"): if features.is_empty_extension(ext): continue if ext.attrib["name"] in exceptext: continue features.require_extension(root, ext.attrib["name"], types, cmds, extnames) f = open(dirname(realpath(__file__)) + "/../src/lib.rs", "w")
def p(self, shareFile): while True: self.command_list() print("waiting for you ") out = input("Please Enter The Name of The Command: ") print(out) if int(out) == 3: return out elif int(out) == 1: path = input( "Please Insert The Name of The Torrent File\n(For returning to the main manu, Insert 0)" ) if path == '0': continue else: name = '' hashedFile = '' count_chunk = 0 with open(path, 'r') as file: name = (file.read().split("\n")[0]) file.seek(0) hashname = (file.read().split("\n")[1]) file.seek(0) count_chunk = int(file.read().split("\n")[2]) file.seek(0) hashedFile = (file.read().split("\n")[3]) payload = { 'id': shareFile.ID, 'ip': shareFile.HOST, 'hash': int(hashname), 'name': name } connect_to = shareFile.next_peers['first']['ip'] t = threading.Thread(target=client.Client( shareFile, connect_to).find_seeder, args=(shareFile, payload)) t.daemon = True t.start() t = threading.Thread(target=self.checker, args=(count_chunk, hashedFile, name, shareFile)) t.daemon = True t.start() elif int(out) == 2: path = input( "Please Insert The Name of The Upload File\n(For returning to the main manu, Insert 0)" ) if path == '0': continue else: if not os.path.isfile(path): print("The ", path, " does not exist") continue if not shareFile.peers: connect_to = shareFile.next_peers['first']['ip'] counter = 0 payload = { 'id': shareFile.ID, 'ip': shareFile.HOST, 'counter': counter } t = threading.Thread(target=client.Client( shareFile, connect_to).find_peers, args=(shareFile, payload, 210)) t.daemon = True t.start() fs = FileSplit(path, 256000, str(shareFile.HOST) + '/output/') number_of_chunks = fs.split() hashedName = None with open(path + ".torrent", "w+") as f: f.write(path + '\n') hashedName = hash(path) % 400 f.write(str(hashedName) + '\n') print(hashedName) f.write(str(number_of_chunks) + '\n') hashfile = commands.Commands().md5hashing(path) f.write(str(hashfile)) if shareFile.previous_node['node']['id'] > shareFile.ID: if shareFile.ID >= hashedName and shareFile.next_peers[ 'first']['id'] > hashedName: self.save_to_database(shareFile, 1, number_of_chunks, hashedName, path) else: self.send_chunks(shareFile, 0, number_of_chunks, hashedName, path) elif shareFile.ID >= hashedName and shareFile.previous_node[ 'node']['id'] < hashedName: self.save_to_database(shareFile, 1, number_of_chunks, hashedName, path) else: self.send_chunks(shareFile, 0, number_of_chunks, hashedName, path) self.uyt(shareFile, number_of_chunks, hashedName, path)
def __init__(self): self.__Alive = True self._commands = commands.Commands() self._playerinfo = playerinfo.Playerinfo()
def __init__(self): self.fs = filesystem.Filesystem() self.cfg = config.Config() self.cmds = commands.Commands() self.board = self.fs.load() self.reader = reader.Reader()
from tempfile import NamedTemporaryFile from tkinter import * import csv import shutil import importlib import commands as com import scraper as scrap root = Tk() # * creates the blank window c = com.Commands() def printMessage(): print("Wow it works") def isInt(s): try: int(s) return True except ValueError: return False def checkURL(): print("Checking URL") # Some Regex Function
#!/usr/bin/env python3 import asyncio import config import commands import discord import pprint import triggers import re config = config.Config() print("Loaded config\n") client = discord.Client() commands = commands.Commands(config.get_gkey()) triggers = triggers.Triggers() def get_command(message): command = message.split(" ", 1)[0] return command[1:] @client.event async def on_ready(): print('logged in as') print(client.user.name) print(client.user.id) print('-------') @client.event async def on_message(message):
self._sock = sock print('[*] Server running on {}'.format(self._port)) return self._sock def __exit__(self, *exc_info): if exc_info[0]: import traceback traceback.print_exception(*exc_info) self._sock.close() if __name__ == '__main__': host = 'localhost' a = handleArgs() with Server(host, a['port']) as s: with db.Database() as database: c = commands.Commands(database) while True: conn, addr = s.accept() msg = conn.recv(1024) try: payload = json.loads(msg.decode('utf-8')) print('payload', payload) response = c.handleCommand(payload) print('response', response) conn.send(json.dumps(response).encode()) except: pass finally: conn.close()
import requests,json,time,commands,rasa import telepot from telepot.loop import MessageLoop with open("config-base.json") as f: config = json.load(f) rasa_url = config["rasa_url"]+"/parse?q=%s&project="+config["rasa_project"] cmd = commands.Commands(config["bot_key"]) nlu = rasa.Rasa(config["bot_key"],rasa_url) print('Servidor inicializado') def handle(message): msg_type,chat_type,chat_id = telepot.glance(message) if "entities" in message and message["entities"][0]['type'] == 'bot_command': cmd.getCommand(message,chat_id) else: nlu.parseMessage(message,chat_id) def on_callback_query(msg): data = msg print(data) if __name__ == "__main__": telegram = telepot.Bot(config["bot_key"]) MessageLoop(telegram, { "chat": handle, "callback_query": on_callback_query }).run_as_thread() while 1: try: time.sleep(10) pass except:
import refresh_api from stream_data import Stream from timed_objects import TimerObjects # --------------------------------------------- Start Settings ---------------------------------------------------- HOST = "irc.chat.twitch.tv" # Hostname of the IRC-Server in this case twitch's PORT = 6667 # Default IRC-Port CHAN = settings.CHAN # Channelname = #{Nickname} NICK = settings.NICK # Nickname = Twitch username PASS = settings.PASS # www.twitchapps.com/tmi/ will help to retrieve the required authkey STREAM = Stream() DISPLAY = api_parse.streamDataDisplay() YT = yt_intro_vid.YTVideo() TIMEOBJS = TimerObjects() COMS = commands.Commands(TIMEOBJS) # --------------------------------------------- End Settings ------------------------------------------------------- # --------------------------------------------- Start Functions ---------------------------------------------------- def send_pong(con, msg): con.send(bytearray('PONG %s\r\n' % msg, 'UTF-8')) def send_message(con, chan, msg, user='******'): con.send(bytearray('PRIVMSG %s :%s\r\n' % (chan, msg), 'UTF-8')) def send_nick(con, nick, user='******'): con.send(bytearray('NICK %s\r\n' % nick, 'UTF-8'))
# A very simple Flask Hello World app for you to get started with... from flask import Flask, redirect, render_template, request, url_for from flask import jsonify from flask import request from flask_sqlalchemy import SQLAlchemy from flask_login import login_user, current_user, LoginManager, UserMixin, login_required, logout_user from flask_migrate import Migrate from werkzeug.security import check_password_hash, generate_password_hash import commands import datetime cmd = commands.Commands() app = Flask(__name__) SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format( username="******", password="******", hostname="animbuddy.mysql.pythonanywhere-services.com", databasename="animbuddy$animBuddyData", #databasename="animbuddy$dummyempty", ) app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI app.config["SQLALCHEMY_POOL_RECYCLE"] = 299 app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db = SQLAlchemy(app) migrate = Migrate(app, db)
"""The entry point of the bot""" # pylint: disable=C0103 import sys import commands import discord prefix = "?" client = discord.Client() cmds = commands.Commands() @client.event async def on_ready(): """Runs when the bot logged in.""" print("Logged in:") print(client.user.name) print(client.user.id) @client.event async def on_message(message): """Runs when a chat message is posted.""" if message.content.split(" ")[0].startswith(prefix): executed = cmds.execute(message.content[len(prefix):]) if executed is not None: is_embed = executed[0] msg = executed[1] if is_embed: await client.send_message(message.channel, embed=msg)