예제 #1
0
 def __init__(self, config: ConfigParser, app: Flask):
     self.config = config
     self.app = app
     self.client = Client()
     self.loop = asyncio.new_event_loop()
     self.loop.run_until_complete(
         self.client.login(config['bot']['token'], bot=True))
예제 #2
0
    def __init__(self):
        self.info = config.CONFIG['bots'][0]
        self.client = Client()
        MainListener(self.client, Manager())
        self.loop = asyncio.get_event_loop()

        self.loop.run_until_complete(self.start())
예제 #3
0
async def init(loop):
    conn = await connect(host=HOST,
                         port=PORT,
                         user=USER,
                         password=PASSWORD,
                         db=DATABASE_NAME,
                         loop=loop)
    client = Client()
    data_collector = {}
    guilds = {}
    world_stat = WorldStat(client)
    items = Items(client)
    builds = Builds(client)
    market_caches = {}
    fissure_caches = {}
    party_caches = {}
    riven_caches = {}

    set_on_guild_join(client, conn, data_collector, guilds, world_stat,
                      TABLE_NAME)
    set_on_guild_remove(client, conn, data_collector, TABLE_NAME)
    set_on_message(client, conn, data_collector, guilds, items, market_caches,
                   builds, world_stat, fissure_caches, party_caches,
                   riven_caches, TABLE_NAME)
    set_on_ready(client, conn, guilds, data_collector, world_stat, TABLE_NAME)
    set_on_reaction_add(client, conn, data_collector, market_caches,
                        fissure_caches, party_caches, riven_caches, guilds,
                        TABLE_NAME)
    set_on_member_join(client, data_collector)
    set_on_voice_state_update(client, data_collector, guilds)
    set_on_message_delete(client, market_caches, fissure_caches, party_caches,
                          riven_caches)
    set_task_1(client, world_stat)

    return client
예제 #4
0
async def main():
    client = Client(intents=Intents(guilds=True))
    client.my_cfg = load_config()
    tree = CommandTree(client)
    init = False

    @client.event
    async def on_ready():
        nonlocal init
        if not init:
            app = await client.application_info()
            client.my_owner_id = app.owner.id

            guild = None # client.get_guild(ID)
            add_vouch_interactions(tree, guild)
            if "not guild" and app.bot_public:
                @tree.command(guild=guild)
                async def invite(ctx: Interaction):
                    """Give an invite link for this bot"""
                    await ctx.response.send_message(
                        oauth_url(
                            app.id,
                            permissions=Permissions(manage_roles=True),
                            scopes=["bot", "applications.commands"]),
                        ephemeral=True)
            await tree.sync(guild=guild)
            init = True

    async with client:
        await client.start(client.my_cfg['bot-token'])
예제 #5
0
    def __init__(self, token, bm, loop, working_path):
        """
        SpeakerBot(token, mm, bm)

        Initializing speaker bot
        Argument:
        - token: String
        - bm: BotManager(bot_manager.py)
        - loop: event loop
        - working_path: working directory path
        :param token, bm, loop, working_path:
        """
        self.info("Lunching SpeakerBot...")
        # instance status
        self.enabled = True
        # init
        self.google_client = texttospeech.TextToSpeechClient()
        self.discord_client = Client()
        self.bm = bm
        self.vg = VoiceGenerator(self.google_client, working_path="{0}/{1}".format(working_path, self.__hash__()))
        # prepare Queue
        self.queue = Queue()
        # speaker init
        self.st = Thread(target=self.speak_thread)
        self.st.start()
        # run
        loop.create_task(self.discord_client.start(token))
        self.info("launched")
예제 #6
0
def generate_oauth():
    client_id = os.getenv("CLIENT_ID", "")
    guild_id = os.getenv("GUILD_ID", "")
    # Has send messages permisison
    permissions = Permissions(permissions=2048)
    Client().get_guild(guild_id)
    generated_url = oauth_url(client_id, permissions)
    print(f"Generated oauth for given client id: {generated_url}")
예제 #7
0
 def __init__(self, bot, config):
     self.bot = bot
     self.config = config
     self.config["embed_colour"] = get_embed_colour(self.config["logo_url"])
     self.client = Client(loop=bot.loop)
     self.client.event(self.on_ready)
     self.client.event(self.on_message)
     bot.loop.create_task(self.client.start(config["token"], bot=False))
예제 #8
0
    def __init__(self, name):
        super(ChatBot, self).__init__(name)
        self.actions = dict()
        self.client = Client()
        self.token = self.read_key()

        # load up the ban list
        self._load_bans()
예제 #9
0
    def __init__(self, config: Config) -> None:
        self.config: Config = config

        self.loop: asyncio.AbstractEventLoop = asyncio.new_event_loop()
        self.client: Client = Client(loop=self.loop)
        self.textChannels: Dict[str, Channel] = {}

        self.zaifStream: ZaifStream = ZaifStream(self.config.currencyPair)
        self.priceHistory: Dict = {}
예제 #10
0
 def __init__(self):
     Bot.instance = self
     self.client = Client()
     # register event listeners
     self.client.event(self.on_ready)
     self.client.event(self.on_message)
     self.client.event(self.on_reaction_add)
     self.client.event(self.on_reaction_remove)
     self.database = Database()
예제 #11
0
def init():
    global currencyPrices
    currencyPrices = []

    global currencies
    currencies = []

    global ffmpegPath
    ffmpegPath = "D:/Software/ffmpeg/bin/ffmpeg.exe"

    global client
    client = Client()
예제 #12
0
async def test_Client_with_default_autopost_error_handler(
    mocker: MockerFixture,
    capsys: CaptureFixture[str],
    session: ClientSession,
    exc: Exception,
) -> None:
    client = Client()
    mocker.patch("topgg.DBLClient._auto_post", new_callable=mock.AsyncMock)  # type: ignore
    dbl = DBLClient(client, "", True, session=session)
    assert client.on_autopost_error == dbl.on_autopost_error
    await client.on_autopost_error(exc)
    assert "Ignoring exception in auto post loop" in capsys.readouterr().err
예제 #13
0
    def __init__(self, name, *args, **kwargs):
        super().__init__("Discord")

        self.__name__ = name
        self.client = Client()
        self.token = kwargs.get("token", None)
        self._config = Config()

        self.groups = {}
        self.cases = {}

        self._run = self.run
 def __init__(self):
     self.client_id = os.environ['DISCORD_CLIENT_ID']
     self.client_secret = os.environ['DISCORD_CLIENT_SECRET']
     self.redirect_uri = os.environ["DISCORD_REDIRECT_URI"]
     self.client = Client()
     self.is_bot = True
     self.logger = InitLogger.instance()
     self.headers = {
         'Content-Type': 'application/json',
         'Authorization': ''
     }
     self.http_client = HttpClient()
     self.api_endpoint = DISCORD_API_ENDPOINT
예제 #15
0
파일: bot.py 프로젝트: NQN-Discord/DemoBot
async def initialise(config, postgres_pool):
    elastic = ElasticSearchClient(config["elastic"]["hosts"])
    bot = Client()

    log.info("Connecting to Redis")
    persistent_redis = await aioredis.create_redis_pool(
        config["persistent_redis_uri"], encoding="utf-8")
    nonpersistent_redis = await aioredis.create_redis_pool(
        config["nonpersistent_redis_uri"], encoding="utf-8")

    log.info("Connecting to PostgreSQL")
    postgres: SQLConnection = SQLConnection(postgres_pool, bot.get_guild,
                                            sql_wrapper("commands"))

    await dpy.connect(bot, nonpersistent_redis, config["discord"]["proxy"],
                      config["discord"]["token"])

    log.info("Connecting to RabbitMQ")
    guild_cache = dpy.GuildCache(bot, nonpersistent_redis)
    rabbit = DemoBaseRabbit(bot, guild_cache, config["rabbit_uri"])

    log.info("Initialising global context")
    bot.global_ctx = GlobalContext.from_databases(
        owner=bot.owner,
        bot_user=bot.user,
        postgres=postgres,
        elastic=elastic,
        persistent_redis=persistent_redis,
        nonpersistent_redis=nonpersistent_redis,
        get_guild=bot.get_guild,
        get_emoji=bot.get_emoji,
        emote_hasher_url=config["hasher_url"],
        webhook_url=config["webhook_url"],
        user_emote_cache_time=config.get("user_emote_cache_time", 10),
        broadcast_prefix=rabbit.send_prefix)

    log.info("Bot initialised, connecting to Discord")
    await guild_cache.load_state_from_redis()
    await bot.global_ctx.aliases.update_alias_servers()

    async def cleanup():
        pass

    dpy.take_over_the_world(rabbit=rabbit,
                            redis=nonpersistent_redis,
                            process_name="demo_base_bot",
                            world_takeover_sleep=config.get(
                                "world_takeover_sleep", 5),
                            cleanup=cleanup())

    log.info("Finished initialising")
예제 #16
0
async def test_Client_with_custom_autopost_error_handler(
    mocker: MockerFixture, session: ClientSession, exc: Exception
) -> None:
    client = Client()
    state = False

    @client.event
    async def on_autopost_error(exc: Exception) -> None:
        nonlocal state
        state = True

    mocker.patch("topgg.DBLClient._auto_post", new_callable=mock.AsyncMock)  # type: ignore
    DBLClient(client, "", True, session=session)
    await client.on_autopost_error(exc)
    assert state
예제 #17
0
def activateBot(
    tokenFilename: str,
    BotType,
):
    """
    Basic bot startup method.
    :param tokenFilename: path where the bot-token is located
    :param BotType: type of bot to instantiate
    """
    with open(tokenFilename) as f:
        token = f.read().rstrip()

    client = Client()
    bot = BotType(client)

    @client.event
    async def on_message(message):
        await bot.executeCommand(message)

    @client.event
    async def on_ready():
        await bot.login()

    client.run(token)
예제 #18
0
    def bot_main():
        print("let us begin")

        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        client = Client(loop=loop)

        @manager.scheduledTask(seconds=5, loop=loop)
        async def backgroung_bot_task():
            global n
            n += 1
            print(i * i)

        @client.event
        async def on_message(msg):
            if msg.author.id == client.user.id:
                return
            print(msg)

        loop.create_task(client.start(input("Bot token please: "), bot=True, reconnect=True))
        loop.run_forever()

        print("out")
예제 #19
0
from discord import Client

from asyncio import sleep
from random import randint

import config

from importlib import import_module  # Using importlib's `import_module` function is preferred over Python's built-in `__import__`

bot = Client()

commands = {}
for file in import_module('os').listdir(
        import_module('os').path.join('.', 'cmds')):
    if file.endswith('.py'):
        cmd = import_module("cmds." + file[:-3])
        # The following code is going to check if the command is valid, if it is, then register it
        if not isinstance(cmd.aliases, list):
            print("Command alias is not a list, skipping " + file)
        elif not isinstance(cmd.name, str):
            print("Command name is not a string, skipping " + file)
        if (isinstance(cmd.aliases, list) and isinstance(cmd.name, str)):
            for alias in cmd.aliases:
                commands[alias] = {
                    "code": cmd.code,
                    "alias": True,
                    "original_name": cmd.name
                }
            commands[cmd.name] = {
                "code": cmd.code,
                "alias": False,
예제 #20
0
파일: app.py 프로젝트: voidpp/scrat
from scrat.components.argument_parser import GentleArgumentParserError
from scrat.components.config import load
from scrat.components.database import Database
from scrat.components.link_cache import LinkCache
from .commands.base import COMMAND_PREFIX, CommandBase
from .commands.command_list import CommandList
from .commands.last_battle_times import LastBattleTimes
from .commands.link import Link
from .commands.online_players import OnlinePlayers
from .context import Context

config = load()

db = Database(str(config.database))

discord_client = Client()
wows_cache = RedisCache(config.redis)
wows_client = Wows(config.wows_token, wows_cache)

link_cache = LinkCache(config.redis)

context = Context(wows_client, link_cache, db, config)

logger = logging.getLogger(__name__)


# move out the event handlers too? inherit from discord.Client


@discord_client.event
async def on_connect():
예제 #21
0
import settings
import utilities
import communication
import authentication
import asyncio
from discord import Client
from threading import Thread

# Extracts the token, and creates directories.
utilities.initialize()
settings_file = settings.get_settings_file()
pycord_settings = settings.extract_settings(settings_file,
                                            utilities.default_settings)
login_token = authentication.extract_token(settings_file)

DiscordClient = Client()
command_queue = []

# Logger creation
logger = utilities.new_logger("pycord-main",
                              use_console=utilities.LOG_TO_CONSOLE)
logger.info(f"Started Pycord daemon at {utilities.get_time()}")
logger.info("Loaded settings.")
logger.info("Attempting to login...")

if login_token == "":
    logger.critical("Invalid token passed! Cannot login to Discord. Exiting.")
    sys.exit(1)


def handle_queue(server: communication.Listener):
예제 #22
0
import schedule
import asyncio

from discord import Client
from typing import Optional, Sequence
from impose.logger import LOGGER
from concurrent.futures import CancelledError

from impose.service import Service
from impose.usecases.task import TaskHandler
from impose.usecases.command import parse
from impose.adapters import Database, Discord
from impose.entities import Task

IMPOSE_TOKEN = "IMPOSE_TOKEN"
CLIENT = Client()


@CLIENT.event
async def on_ready() -> None:
    LOGGER.info(f"Logged-in as {Service.get_instance().discord.user}")


@CLIENT.event
async def on_message(message) -> None:
    service = Service.get_instance()

    if message.author == CLIENT.user:
        return

    cmd = parse(message.content)
예제 #23
0
from discord import Client, Message, Object, TextChannel
from discord.errors import NotFound
from typing import Optional

DISCORD = Client()


def with_discord() -> Client:
    """
    Get a connection to discord
    """
    return DISCORD


async def get_channel(id_: int) -> Optional[TextChannel]:
    """
    Retrieve a channel by its ID
    :param id_: the channel's ID
    """
    try:
        channel = await DISCORD.fetch_channel(id_)
    except NotFound:
        return None
    if not isinstance(channel, TextChannel):
        return None

    # Populate the guild
    if type(channel.guild) == Object:
        channel.guild = await DISCORD.fetch_guild(channel.guild.id)

    return channel
예제 #24
0
from discord.message import Message
import requests
from bs4 import BeautifulSoup
import urllib.request
from discord.ext import commands
from discord import Client
import random
import numpy as np
from dnd import generate_monster_block, Monster
from dotenv import load_dotenv
load_dotenv()
bot = commands.Bot(command_prefix="!")

intents = discord.Intents.default()
intents.members = True
client = Client(intents=intents)
token = os.getenv("DISCORD_TOKEN")
channel_id = os.getenv("CHANNEL_ID")


def get_commander_dataset():
    commander = list()
    apiurl = 'https://api.scryfall.com/cards/search?q=is%3Acommander+legal%3Acommander'
    while apiurl:
        # la request
        datacommander = requests.get(apiurl).json()
        #  les datas
        commanderprov = [(card['name'], card['related_uris']['edhrec'])
                         for card in datacommander["data"]]
        commander = commander + commanderprov
        if datacommander["has_more"]:
예제 #25
0
import uuid
import pytz
from pytz import timezone
from datetime import datetime, timedelta
from bot_vars import eightball_answers, command_list
from keep_alive import keep_alive
from rt import get_ratings
from PIL import Image
from io import BytesIO
from discord import Client, Game, Intents, Embed
# from discord.ext import tasks
from discord_slash import SlashCommand
# from discord_slash.utils.manage_commands import create_option

# Set "Playing" status. Apparently custom statuses do not work for bots (yet?).
mikebot = Client(activity=Game(name='with Python'), intent=Intents.default())
slash = SlashCommand(mikebot, sync_commands=True)

# Used for tasks/loops
last_posted_games_filename = 'last_posted_games_time.txt'
datetime_format = '%Y-%m-%d %H:%M:%S.%f'
timezone_hour_difference = timedelta(hours=5)
posting_interval_free_games = timedelta(hours=12)
loop_delay = 3600
cthulhu_channel_id = 456550971565277194

# Reddit credentials
reddit = praw.Reddit(client_id=os.environ['REDDIT_ID'],
                     client_secret=os.environ['REDDIT_SECRET'],
                     username=os.environ['REDDIT_USER'],
                     password=os.environ['REDDIT_PASS'],
예제 #26
0
log_host, log_port = os.getenv('LOG_URL').rsplit(':', 1)
syslog = SysLogHandler(address=(log_host, int(log_port)))
log_format = '%(asctime)s vast-ai dungeon_worker: %(message)s'
log_formatter = logging.Formatter(log_format, datefmt='%b %d %H:%M:%S')
syslog.setFormatter(log_formatter)

logger = logging.getLogger()
logger.addHandler(syslog)
logger.setLevel(logging.INFO)

import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.DEBUG)

max_history = 20
generator = GPT2Generator()
client = Client(intents=Intents.default())
logger.info('Worker instance started')


def escape(text):
    text = re.sub(r'\\(\*|_|`|~|\\|>)', r'\g<1>', text)
    return re.sub(r'(\*|_|`|~|\\|>)', r'\\\g<1>', text)


@client.event
async def on_ready():
    # connect & clear redis queue
    logger.info('Connecting to redis')
    queue = await aioredis.create_redis_pool(os.getenv('REDIS_URL'))
    await queue.client_setname('worker')
    loop = asyncio.get_event_loop()
예제 #27
0
import sys
import asyncio
from dataclasses import dataclass, field
from asyncio import Task
from typing import Dict, Optional, Set

import toml
from discord import (Client, Intents, Guild, Member, Message, TextChannel,
                     RawReactionActionEvent)

cfg = toml.load('cfg.toml')
client = Client(intents=Intents(members=True, reactions=True, guilds=True))


@dataclass
class GuildCtx:
    # at the disco
    panic: bool = False
    reset: Optional[Task] = None
    members: Set[Member] = field(default_factory=lambda: set())


@dataclass
class Incident:
    purger: Task
    members: Set[Member] = field(default_factory=lambda: set())


joins: Dict[Guild, GuildCtx] = {}
incidents: Dict[int, Incident] = {}
from discord import Client

from automation.functions import load_config
from automation.message.unknown_message import UnknownMessage
from automation.parser.message_parser import MessageParser

if __name__ == '__main__':
    config = load_config()
    dc = Client()

    @dc.event
    async def on_ready() -> None:
        channel = dc.get_channel(config['discord']['channel'])
        messages = []

        async for message in channel.history():
            content = message.content
            parent_content = message.reference.resolved.content if message.reference is not None else None
            messages.append((content, parent_content))

        for content, parent_content in messages:
            try:
                MessageParser.parse(content, parent_content)
                continue
            except (UnknownMessage, AssertionError):
                print(f'{content}\n-----\n{parent_content}\n\n\n')

        await dc.close()

    dc.run(config['discord']['token'], bot=False)
#!/usr/bin/env python3

from discord import Client
import sys

chat_id = None
output = None

client = Client()

@client.event
async def on_ready():
    print('Logged in as: ' + client.user.name)
    print('------')
    channel = None
    for ch in client.private_channels:
        if ch.id == chat_id:
            channel = ch
            print('Channel found, retrieving history...')
            break
    else:
        sys.exit('Channel not found!')

    with open(output, 'w') as out:
        async for message in client.logs_from(channel, limit=9999999999999):
            out.write(message.timestamp.strftime('%d/%m/%Y %H:%M:%S%z') + ' - '
                      + message.author.name + ': ' + message.content + '\n')
    print('done')
    await client.close()

예제 #30
0
def main():
    pokemon_list_dir = Path('lts/pokemon.json')
    bots: [int] = [716390085896962058]

    def read_pokemon() -> [str]:
        if os.path.exists(pokemon_list_dir):
            with open(pokemon_list_dir, 'r') as f:
                pf = json.load(f)
            return pf
        pokeformat.format_poke()
        read_pokemon()

    client: Client = Client()
    pokemon: [str] = read_pokemon()

    def special_pokemon() -> {str}:
        special_forms = [
            'Alolan',
            'Galarian',
            'Shadow'
        ]
        temp_dict: {str} = {}
        for mon in pokemon:
            processed_msg = str(mon).split(' ')
            if processed_msg[0] in special_forms:
                temp_dict[processed_msg[1]] = mon
        return temp_dict

    special_mons = special_pokemon()

    @client.event
    async def on_ready():
        print(f'Initialized PokeHelper {__version__}')

    @client.event
    async def on_message(msg):
        if msg.author.id in bots:
            if 'The pokémon is' in msg.content:
                content = str(msg.content).strip().strip('.').split(' ')
                pokemon_hint = ''
                for msg_piece in content:
                    if '_' in msg_piece:
                        if 'é' in msg_piece:
                            await msg.channel.send('[\'Flabebe\']')
                            return
                        msg_piece = msg_piece.replace('\\', '')
                        pokemon_hint += (' ' + msg_piece)
                        pokemon_hint = pokemon_hint.strip()
                final_mons = search_mons(pokemon_hint)
                for mon in final_mons:
                    if mon in special_mons:
                        final_mons.append(special_mons[mon])
                print(str(final_mons).replace('_', ''))
                await msg.channel.send(str(final_mons).replace('_', ''))

    def search_mons(hint) -> [str]:
        possible_mons = pokemon
        for i in range(len(hint)):
            if not (hint[i] == '_'):
                new_possible_mons = []
                for p in possible_mons:
                    if len(hint) == len(p) and hint[i] == p[i]:
                        new_possible_mons.append(p)
                possible_mons = new_possible_mons
        return possible_mons

    client.run(str(input('Please input bot Token: ')))