Exemple #1
0
def load_opus_lib(opus_libs=OPUS_LIBS):
    if platform.system() == 'Linux':
        print("Linux detected")

        try:
            shutil.copy("./.apt/lib/x86_64-linux-gnu/libusb-1.0.so.0",
                        "./.apt/usr/lib/x86_64-linux-gnu/libusb-1.0.so.0")
            shutil.copy(
                "./.apt/usr/lib/x86_64-linux-gnu/pulseaudio/libpulsecommon-11.1.so",
                "./.apt/usr/lib/x86_64-linux-gnu/libpulsecommon-11.1.so")
            shutil.copy("./.apt/lib/x86_64-linux-gnu/libslang.so.2",
                        "./.apt/usr/lib/x86_64-linux-gnu/libslang.so.2")
        except FileNotFoundError:
            pass

        for opus_lib in OPUS_LIBS_LINUX:
            try:
                opus.load_opus(opus_lib)
                print("Tried %s" % opus_lib)
                return
            except OSError:
                raise RuntimeError('Could not load an opus lib. Tried %s' %
                                   (', '.join(opus_libs)))

    if opus.is_loaded():
        print('Opus loaded')
        return True
Exemple #2
0
async def play_sound(ctx, file_name: str):
    opus = ctypes.util.find_library('opus')
    load_opus(opus)

    if not exists(f"sounds/{file_name}.mp3"):
        await ctx.send("This sound has been injected!")
        return

    if not ctx.author.voice and not ctx.author.voice.channel:
        await ctx.send(f"{ctx.author.name} is not in a voice channel")

    client.currently_playing = True

    voice_channel = ctx.author.voice.channel

    vc = await voice_channel.connect()
    vc.play(
        FFmpegPCMAudio(executable=join(script_path, "bin", "ffmpeg"),
                       source=join(script_path, "sounds", f"{file_name}.mp3")))

    while vc.is_playing():
        await sleep(.1)

    client.currently_playing = False

    await vc.disconnect()
    await ctx.message.delete()
Exemple #3
0
def main():
    """
    The main entry point.

    Invoke using `python -m discobot`.
    """
    parser = argparse.ArgumentParser(
        prog='discobot', description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument(
        'config', nargs='?', type=argparse.FileType('r'),
        default='config.yaml', help='configuration file to use')
    args = parser.parse_args()

    config = yaml.load(args.config.read())
    args.config.close()

    kwargs = config.get('log', {}).copy()
    level = getattr(logging, kwargs.pop('level', 'info').upper(), logging.INFO)
    logging.basicConfig(level=level, **kwargs)

    if not opus.is_loaded():
        opus.load_opus(config['opus_library_path'])

    bot.configure(config)
    bot.run(config['bot']['token'])
Exemple #4
0
    def __init__(self, key_store_path: str):
        if not opus.is_loaded():
            opus.load_opus()

        keys = []
        with open(key_store_path, 'r') as key_file:
            keys = key_file.readlines()
            for idx, key in enumerate(keys):
                keys[idx] = key.split(":")[1].strip()

        self.bot_token = keys[0]
        self.bot_id = keys[1]

        self.song_list = []
        self.stop = False
        self.is_playing = False
        self.player = None

        self.admin_roles = ["Butcher of Reports", "Admin"]
        self.image_store_path = "Other_Images"
        self.images = Images(self.image_store_path)

        self.image_processing = ImageProcess()
        self.reddit = RedditBot(id=keys[2],
                                secret=keys[3],
                                user=keys[4],
                                password=keys[5],
                                agent=keys[6])
Exemple #5
0
async def on_ready():
    load_opus(find_library('opus'))
    prep_tmp_directory()
    if client.user.name != NAME:
        await client.edit_profile(username=NAME)
    print('{} with id {} is ready, myan!'.format(client.user.name, client.user.id))
    if not DISABLE_STATUS_LOOP:
        await shuffle_status_and_loop()  # Loops forever
Exemple #6
0
async def on_ready():
    ''' Executed when the bot successfully connects to Discord. '''
    print('Logged in!\nName: {}\nId: {}'.format(client.user.name,
                                                client.user.id))
    if sys.maxsize > 2**32:
        opus.load_opus('libopus-0.x64.dll')
    else:
        opus.load_opus('libopus-0.x86.dll')
Exemple #7
0
async def on_ready():
    ''' Executed when the bot successfully connects to Discord. '''
    print('Logged in!\nName: {}\nId: {}'.format(
        client.user.name, client.user.id))
    if sys.maxsize > 2**32:
        opus.load_opus('libopus-0.x64.dll')
    else:
        opus.load_opus('libopus-0.x86.dll')
Exemple #8
0
async def on_ready():
    load_opus(find_library('opus'))
    prep_tmp_directory()
    if client.user.name != NAME:
        await client.edit_profile(username=NAME)
    print('{} with id {} is ready, myan!'.format(client.user.name,
                                                 client.user.id))
    if not DISABLE_STATUS_LOOP:
        await shuffle_status_and_loop()  # Loops forever
Exemple #9
0
def load_opus_lib(opus_libs=OPUS_LIBS):
    if platform.system() == 'Windows': return True
    if opus.is_loaded(): return True
    for opus_lib in opus_libs:
        try:
            opus.load_opus(opus_lib)
            return True
        except OSError:
            raise RuntimeError(f"Could not load an opus lib ({opus_lib}). Tried {', '.join(opus_libs)}")
Exemple #10
0
def load_opus_lib(opus_libs=OPUS_LIBS):
    if opus.is_loaded():
        return True
    for opus_lib in opus_libs:
        try:
            opus.load_opus(opus_lib)
            return
        except OSError:
            pass
    raise RuntimeError('Could not load an opus lib. Tried %s' % (', '.join(opus_libs)))
Exemple #11
0
def load_opus_lib():
    if opus.is_loaded():
        return True

    for opus_lib in OPUS_LIBS:
        try:
            opus.load_opus(opus_lib)
            return
        except OSError:
            pass
Exemple #12
0
def load_opus_lib(opus_libs=OPUS_LIBS):
    if opus.is_loaded():
        return True
    for opus_lib in opus_libs:
        try:
            opus.load_opus(opus_lib)
            return
        except OSError:
            pass
    raise RuntimeError("OPUS 라이브러리를 로드하는데 실패했어용. 이것들을 시도해봤어용: {}".format(
        ", ".join(opus_libs)))
def load_opus_lib(opus_libs=OPUS_LIBS):
    if opus.is_loaded():
        return True
    for opus_lib in opus_libs:
        try:
            opus.load_opus(opus_lib)
            log.debug("Loaded opus lib \"{}\"".format(opus_lib))
            return
        except OSError:
            pass
    log.critical("Could not load an opus lib. Tried {}".format(", ".join(opus_libs)))
    os._exit(1)
Exemple #14
0
def load_opus_lib(opus_libs=OPUS_LIBS):
    if opus.is_loaded():
        return True

    for opus_lib in opus_libs:
            try:
                opus.load_opus(opus_lib)
                return
            except OSError:
                pass

    raise RuntimeError('Could not load an opus lib. Tried %s' %(', '.join(opus_libs)))
Exemple #15
0
def load_opus_lib(opus_libs=OPUS_LIBS):
    if opus.is_loaded():
        return True
    for opus_lib in opus_libs:
        try:
            opus.load_opus(opus_lib)
            log.debug("Loaded opus lib \"{}\"".format(opus_lib))
            return
        except OSError:
            pass
    log.critical("Could not load an opus lib. Tried {}".format(", ".join(opus_libs)))
    os._exit(1)
Exemple #16
0
def load_opus_lib(opus_libs=OPUS_LIBS):
    if opus.is_loaded():
        return True

    for opus_lib in opus_libs:
        try:
            opus.load_opus(opus_lib)
            return
        except OSError:
            pass

    raise RuntimeError('opus libを読み込めませんでした。試した%s' % (', '.join(opus_libs)))
Exemple #17
0
def load_opus_lib(opus_libs=OPUS_LIBS):
    if opus.is_loaded():
        return True

    for opus_lib in opus_libs:
        try:
            opus.load_opus(opus_lib)
            return True
        except OSError:
            pass

    raise RuntimeError("Could not load an opus lib. Tried {0}".format(
        ", ".join(opus_libs)))
Exemple #18
0
def load_opus_lib(opus_libs=OPUS_LIBS):
    if opus.is_loaded():
        print("libopus loaded")
        return True

    for opus_lib in opus_libs:
        try:
            opus.load_opus(opus_lib)
            return
        except OSError:
            pass
        
    raise RuntimeError("Couldn't load opuslib. Tried %s" % (', '.join(opus_libs)))
Exemple #19
0
async def on_ready():
    print('Logged in as ' + client.user.name + ' (ID:' + client.user.id +
          ') | Connected to ' + str(len(client.servers)) +
          ' servers | Connected to ' +
          str(len(set(client.get_all_members()))) + ' users')
    print('--------')
    print('Current Discord.py Version: {} | Current Python Version: {}'.format(
        discord.__version__, platform.python_version()))

    if sys.maxsize > 2**32:
        opus.load_opus('libopus-0.x64.dll')
    else:
        opus.load_opus('libopus-0.x86.dll')
Exemple #20
0
def load_opus_lib(opus_libs=OPUS_LIBS):
    if opus.is_loaded():
        return True

    for opus_lib in opus_libs:
        try:
            opus.load_opus(opus_lib)
            return
        except OSError:
            pass

    raise RuntimeError('No se pudo cargar una librería de opus. Intentó %s' %
                       (', '.join(opus_libs)))
Exemple #21
0
def load_opus_lib(opus_libs=OPUS_LIBS):
    if opus.is_loaded():
        print("Opus Already Loaded")
        return True

    for opus_lib in opus_libs:
        try:
            opus.load_opus(opus_lib)
            print("Opus loaded with lib {}".format(opus_lib))
            return
        except OSError:
            print("OS ERROR!")
            return

    raise RuntimeError('Could not load an opus lib. Tried %s' %
                       (', '.join(opus_libs)))
Exemple #22
0
    def __init__(self, sparcli):
        self.sparcli = sparcli
        self.voice = {}

        # Start OPUS if not loaded
        if not opus.is_loaded():
            opus.load_opus(find_library('opus'))

        # Load what VCs it's already in
        for i in self.sparcli.servers:

            # Set up a nice dictionary for storage of information
            voiceClientInServer = self.sparcli.voice_client_in(i)
            self.voice[i] = ServerVoice(bot=self.sparcli,
                                        server=i,
                                        voiceClient=voiceClientInServer)
Exemple #23
0
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('On servers:')
    for s in client.guilds:
        print('- %s' % s.name)
    print('----------')
    if sys.maxsize > 2**32:
        print('Loading 64-bit opus...')
        opus.load_opus('./libopus-0.x64.dll')
        print('Loading complete')
    else:
        print('Loading 32-bit opus...')
        opus.load_opus('./libopus-0.x86.dll')
        print('Loading complete')
    print('----------')
Exemple #24
0
async def on_ready():
    """Pretty self-explanatory: prints turbot ID and loads the opus module

    :returns: nothing
    """
    print(client.user.name)
    print(client.user.id)
    print('------')
    #if sys.maxsize > 2**32:
    opus.load_opus('libopus-0.x64.dll')
    #else:
    #opus.load_opus('libopus-0.x86.dll')
    if discord.opus.is_loaded():
        print("Opus module loaded")
    else:
        print("Error : opus module couldn't be loaded")
    print('------')
Exemple #25
0
async def load_opus_lib(opus_libs=OPUS_LIBS):
    try:
        if opus.is_loaded():

            return True

        for opus_lib in opus_libs:
            try:
                opus.load_opus(opus_lib)
                return
            except OSError:
                pass

        raise RuntimeError('Could not load an opus lib. Tried %s' %
                           (', '.join(opus_libs)))
    except Exception as e:
        print(str(e), flush=True)
Exemple #26
0
def load_opus_lib(opus_libs):
    """ TODO """
    if opus_libs is None:
        opus_libs = OPUS_LIBS

    if opus.is_loaded():
        return True

    for opus_lib in opus_libs:
        try:
            opus.load_opus(opus_lib)
            return
        except OSError:
            pass

    raise RuntimeError("Could not load an opus lib. Tried %s" %
                       (', '.join(opus_libs)))
Exemple #27
0
	async def on_ready(self):
		""" Retrieve sibling cogs and perform setup before the bot runs.

		At this point, libopus should have been loaded if it was detected by
		Discord. Otherwise, the path will be grabbed from the config file (it
		must be defined at this point).

		:raises RuntimeError: If libopus could still not be loaded, or no path
		                      was defined in the config, an error is raised.
		"""
		self.send_message = self.bot.get_cog('Text').send_message
		if opus.is_loaded():
			return

		path = config.get('opus')
		if path:
			opus.load_opus(path)

		if not opus.is_loaded():
			raise RuntimeError('Could not load libopus.')
Exemple #28
0
async def on_ready():
    #channel = discord.Channel()
    #aerver = discord.Server()
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')
    #await client.change_status(game=discord.Game(name='Robot Factory on Hard'))
    stat = open("status.txt", "r")
    await bot.change_status(game=discord.Game(name=stat.read()))
    stat.close()
    opus.load_opus("C:/NeatoBot/discord/bin/libopus-0.x86.dll")
    if opus.is_loaded():
        await bot.send_message(generalChannel, "Successfully loaded the Opus library.")
    #await bot.send_message(generalChannel, "Read status")
    #await bot.send_message(generalChannel, "Set status")
    #await bot.send_message(generalChannel, "First init of chat AI")
    #await bot.send_message(generalChannel, "Loaded commands")
    voiceClient = "none"
    await bot.send_message(generalChannel, "Combot fully loaded!")
Exemple #29
0
def load_opus_lib():

    opus_libs = [
        'libopus-0.x86.dll', 'libopus-0.x64.dll', 'libopus-0.dll',
        'libopus.so.0', 'libopus.0.dylib'
    ]

    if opus.is_loaded():
        print('Opus loaded')
        return True

    for opus_lib in opus_libs:
        try:
            opus.load_opus(opus_lib)
            print("Manually loaded {}".format(opus_lib))
            return
        except OSError:
            pass

    raise RuntimeError('Could not load an opus lib. Tried %s' %
                       (', '.join(opus_libs)))
Exemple #30
0
    def __init__(self, bot: commands.Bot) -> None:
        super().__init__(bot)

        if sys.platform == "linux":
            load_opus("libopus.so.0")

        # Create SoundDirectory instance for each subdirectory
        self.sub_dirs = [
            SoundDirectory(directory=subdir.directory,
                           header=subdir.directory.upper(),
                           aliases=subdir.aliases,
                           path=subdir.path,
                           color=self.generate_hex_color_code(
                               subdir.directory)) for subdir in SOUND_SUB_DIRS
        ]

        # Per-guild audio players. Key: Guild ID
        self.players: Dict[int, AudioPlayer] = {}

        # Number of sounds played by guilds in the current session
        self.played_count: DefaultDict[int, int] = defaultdict(
            int)  # Key: Guild ID. Value: n times played
Exemple #31
0
async def on_ready():
    ram.debug = C.is_test
    await other.busy()
    log.I(
        f'Logged in as {C.client.user} (id: {C.client.user.id}, Test: {C.is_test})'
    )
    prepare_const2()
    emj.prepare()
    await ev.load()
    ram.debug = ram.debug or C.is_test
    if not discord__opus.is_loaded():
        lb = find_library("opus")
        log.jD('opus lib: ', lb)  # i can't find it on heroku
        if lb:
            discord__opus.load_opus(lb)
        else:
            log.jI('opus lib not load!')
    ev.start_timers()
    log.I('Beckett ready for work now, after starting at ',
          ram.t_start.strftime('[%d/%m/%y %T]'))
    log.p('======= ' * 10)
    await test_fun()  # for debugging an testing
    C.Ready = True
    await other.test_status(ram.game)
Exemple #32
0
 def load_opus(self):
     opus_path = find_library('opus')
     opus.load_opus(opus_path)
     if not opus.is_loaded():
     	print('Opus was not loaded')
     	self.bot.loop.stop()
Exemple #33
0
import json
import logging

from discord import opus
from discord.ext import commands

from disco import discobot

with open('config.json') as f:
    config = json.load(f)

format = '%(asctime)s ::%(levelname)s:: %(message)s'
datefmt = '%Y-%m-%d %H:%M:%S'
level = getattr(logging, config.get('log-level', 'info').upper())
logging.basicConfig(format=format, datefmt=datefmt, level=level)

if not opus.is_loaded():
    opus.load_opus(config['opus-library-path'])

bot = discobot.DiscoBot(commands.when_mentioned)

import disco.events
import disco.commands
Exemple #34
0
async def on_connect():
    print("Attempting to load OPUS...")
    opus.load_opus(ctypes.util.find_library("opus"))
    print("OPUS loaded: " + str(opus.is_loaded()))
from collections import OrderedDict
from configparser import ConfigParser, NoOptionError, NoSectionError
from hashlib import md5
from random import randint
from tempfile import gettempdir

from discord import ChannelType, opus
from yandex_speech import TTS

from .cmdprocessor import CommandProcessor
from .mydiscord import MyDiscord

tts_voices = ['jane', 'oksana', 'alyss', 'omazh', 'zahar', 'ermil']

if not opus.is_loaded():
    opus.load_opus('voice')

config = ConfigParser()
config.read_file(codecs.open('config.ini', 'r', 'utf-8'))

client = MyDiscord()
try:
    client.token = config.get('discord', 'token')
except (NoSectionError, NoOptionError):
    print("No config option - discord/token")

voice = None
voice_volume = 1.0
try:
    voice_volume = float(config.get('voice', 'volume')) / 100.0
except (NoSectionError, NoOptionError):
Exemple #36
0
from aiohttp import get
from discord import Client, opus, utils, VoiceClient
import asyncio
from os import environ, listdir
from importlib import import_module, reload

opus.load_opus('/usr/lib/x86_64-linux-gnu/libopus.so.0')

class Bot(Client):
    def __init__(self, prefix, token):
        Client.__init__(self)
        self.prefix = prefix
        self.token = token
        self.plugins = []
        self.playlist = set()

        self.load_plugins()

    def load_plugins(self):
        self.plugins = [import_module('plugins.%s' % module.replace('.py', '')) for module in listdir('plugins/') if '.py' in module and '__' not in module]

        for plugin in self.plugins:
            plugin.on_load(self)

        print('Loaded: %s plugins' % len(self.plugins))


    @asyncio.coroutine
    async def on_message(self, message):
        msg = message.content.split(' ')
        cmd_prefix = msg[0][0]
Exemple #37
0
 def check_opus():
     if not opus.is_loaded():
         opus.load_opus("dll/opus/libopus-0.dll")
     return opus.is_loaded()
Exemple #38
0
 async def on_ready(self):
     # self.send_log = ExtModule.get_send_log(self)
     opus.load_opus('libopus.so.0')  # the opus library
     print('soundboard cog is ready.')