Пример #1
0
        command: discord.app_commands.Command[Any, ..., Any],
        **options: str,
    ) -> None:

        data: ApplicationCommandInteractionPayload = {
            "id": 0,
            "application_id": 0,
            "token": "",
            "version": 1,
            "type": 2,
            "data": self._get_command_data(command, self._get_command_options(**options)),
        }
        super().__init__(data=data, state=client._connection)


client = discord.Client(intents=discord.Intents.default())


class MockTree(discord.app_commands.CommandTree):
    last_exception: Optional[discord.app_commands.AppCommandError]

    async def call(self, interaction: discord.Interaction) -> None:
        self.last_exception = None
        return await super().call(interaction)

    async def on_error(
        self, interaction: discord.Interaction, error: discord.app_commands.AppCommandError
    ) -> None:
        self.last_exception = error

import discord
from discord.ext.commands import bot
from discord import game
from discord.ext import commands
import asyncio
import platform
import colorsys
import random
import time

client = commands.Bot(command_prefix='+', case_insensitive=True)
Client = discord.client(782859586281275422)
Client = discord.client(782859586281275422)
Clientdiscord = discord.Client(782859586281275422)


@client.event
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('--------')
    print('CREATED AND HOSTED BY SUBHANKAR DAS')


@client.command(pass_context=True)
@commands.has_permissions(kick_members=True)
async def userinfo(ctx, user: discord.Member):
    r, g, b = tuple(
Пример #3
0
import discord, os, re
from modules import helper

CLIENT = discord.Client()
FLAG_EMOJI = "\N{eyes}"


@CLIENT.event
async def on_ready():
    print("Logged in User: {0.user} | {0.user.id}".format(CLIENT))


@CLIENT.event
async def on_message(message):
    if message.channel.name == "secret-nazi-log":
        return

    githubString = helper.get_github_string(message.content)
    if githubString is None:
        return

    logs = helper.run_truffle_hog(githubString)
    if logs is not None:
        await message.add_reaction(FLAG_EMOJI)
        await helper.message_secret_nazi_channel(message.guild, logs,
                                                 githubString)


CLIENT.run(os.environ["SECRETFINDERBOTTOKEN"])
Пример #4
0
import asyncio
import time, os
import json
import pathlib
import pymysql

from bs4 import BeautifulSoup as bs
import lxml
from selenium import webdriver
import numpy as np
import pandas as pd
import pickle

from gbunium import *

client = discord.Client()  # 디스코드 연동


async def make_embed(article):
    global HOST, USER, PW, DB, CHARSET

    title = article['title']
    content = article['content']
    file_url = article["file_url_list"][0]
    author_url = f"http://www.ilbe.com/list/animation?search={article['author']}&searchType=nick_name"

    embed = discord.Embed(color=0xffffff)
    embed.set_author(name=title, url=author_url)
    embed.set_footer(text=f"{article['author']}")

    # Embed에 삽입, 이미지가 없을경우 예외처리
Пример #5
0
import discord
import logging
crae = discord.Client()
token = input("Bot Token :")
hiddenChannel = discord.Object(id="432132167792066560")


async def GamePresence():
    await crae.wait_until_ready()
    await crae.change_presence(game=discord.Game(name='With Shadows'))


@crae.event
async def on_ready():
    TheMessage = "blank"
    while TheMessage != "exit":
        TheMessage = input()
        await crae.send_message(hiddenChannel, TheMessage)


crae.loop.create_task(GamePresence())
crae.run(token)
Пример #6
0
import os
import discord
import paramiko
from ansitoimg.render import ansiToRaster

TOKEN = os.getenv('DISCORD_TOKEN')
SLASHEM_USER = os.getenv('USER')
SLASHEM_PASS = os.getenv('PASS')
DISCORD_CLIENT = discord.Client()
SSH_CLIENT = paramiko.SSHClient()


@DISCORD_CLIENT.event
async def on_ready() -> None:
    print(f'{DISCORD_CLIENT.user} is connected.\n')


@DISCORD_CLIENT.event
async def on_message(message: str) -> None:
    # ignore messages from ego
    if message.author == DISCORD_CLIENT.user:
        return

    # todo, parse message content and run discord cmd on ssh
    if message.content == 'slashem!':
        slashem_screen = call_ssh(message.content)
        await message.channel.send(slashem_screen)


def call_ssh(slashem_command: str) -> str:
    screen = "Something went wrong"
Пример #7
0
            winrate=0.0,
            score=0,
        )
        session.add(new_user)
    else:
        loser.winrate = round(loser.wins / (loser.loses + 1), 1) * 100
        loser.loses += 1
        if loser.score != 0:
            loser.score -= 5
    session.commit()

    return


#DISCORD PART
client = discord.Client(activity=discord.Game("$start to start the game"))


@client.event
async def on_ready():
    print(f'Ready with {client.user}')


@client.event
async def on_message(message):
    if message.author == client.user:
        return

    channel = message.channel
    host = message.author
    host_mention = f"<@!{host.id}>"
Пример #8
0
import discord
import asyncio
import re
import namechanger
import reactions
from constants import Constants
#import questions

with open("config.txt") as f:
    TOKEN = f.readlines()[0].strip()

Constants.client = discord.Client()


@Constants.client.event
async def on_message(message):
    try:
        # we do not want the bot to reply to itself
        if message.author == Constants.client.user:
            return

        content = message.content.lower()

        await reactions.check_reactions(message)

        #await questions.onmessage(message)

        if "bot" not in message.channel.name:
            return

        if content.startswith(".help"):
Пример #9
0
import ENUM
import dataBASS
import Verify
import ContestManager
import questionManager
import BigDisCommand as cmd
from util import *
import GuessNumberGame as GNG

DEB = ""  # Before Command
NAME = "OTOG - One Tambon One Grader"


thisIntents = discord.Intents.default()
thisIntents.members = True
client = discord.Client(intents=thisIntents)


@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    dataBASS.loadFile()
    ContestManager.reloading()
    client.loop.create_task(cmd.botStatus(client))
    await client.Set_Bot_Namae(NAME)


@client.event
Пример #10
0
from __future__ import annotations

import asyncio
import logging
import sys
import time
from argparse import ArgumentParser
from configparser import ConfigParser

import discord

from evelyn_reminder.client.bot import Bot, Embed

logging.basicConfig(format='[%(asctime)s|%(levelname)s|%(name)s] %(message)s', level=logging.INFO, stream=sys.stdout)
CLIENT = discord.Client(intents=discord.Intents(guilds=True, emojis=True, guild_messages=True))
BOT: Bot


def main() -> None:
    global BOT
    # read config
    parser = ArgumentParser(add_help=False)
    parser.add_argument('config', help='configuration file')
    args = parser.parse_args()
    config = ConfigParser()
    config.read(args.config)
    # setup application
    BOT = Bot(
        netloc=config.get('DEFAULT', 'evelyn_netloc'),
        base_path=config.get('DEFAULT', 'evelyn_base_path'),
Пример #11
0
import discord as dc
import re

from expr import Calculator

START_SYMBOL = '='
repeat_regex = re.compile(r'^[xr](\d+)(.+)$', re.IGNORECASE)

client = dc.Client()


@client.event
async def on_ready():
    print(f'Logged in as {client.user}. Ready.')


def calculate(expression: str) -> str:
    calc = Calculator(expression)
    calc.calculate()
    return f'Result: {calc.result}\nDetails: {calc.details}'


def repeat(times: int, expression: str) -> str:
    REPEAT_LIMIT = 10

    if times < 1:
        raise ValueError('Incorrect repeat number')
    elif times > REPEAT_LIMIT:
        raise ValueError(f'Sorry, the current repeat limit is {REPEAT_LIMIT}')
    else:
        calc = Calculator(expression)
Пример #12
0
import os


##関数領域##
def game1(x):  #数当て用関数 エラーは値が入ってないエラーなのでコマンドを送れば問題はない

    game1_rand = random.randint(1, 100)
    game1_hit = True
    if (game1_rand != x):
        game1_hit = False
    return game1_hit


##クラス定義領域##
###変数指定領域###
client = discord.Client()  ##discordのオブジェクト生成
prefix = '!!'  ##コマンドの頭
member = []  ##メンバーリスト
notoinmess = 'CODMから逃げるな'  ##メッセージ
times = [1, 60, 3600, 86400]
#トークン設定#
bot_token = os.environ['DISCORD_BOT_TOKEN']

embed1 = discord.Embed(title="予定表の提出",
                       description="予定を教えてください。",
                       color=0xff7b7b)
embed2 = discord.Embed(title="お知らせ",
                       url="https://forms.gle/TgTs2kRdixnDYe49A",
                       description="来週の予定を提出してください",
                       color=0x008080)
Пример #13
0
# -*- coding:utf-8 -*-
# 가끔가다 애가 인코딩을 잘못 읽어서 오류를 냅니다. 그것을 대비하기 위해 'utf-8'으로 읽으라고 선언합니다.
import discord, asyncio  # 디스코드 모듈과, 보조 모듈인 asyncio를 불러옵니다.
import time
import os

client = discord.Client()  # discord.Client() 같은 긴 단어 대신 client를 사용하겠다는 선언입니다.


@client.event
async def on_ready():  # 봇이 준비가 되면 1회 실행되는 부분입니다.
    # 봇이 "반갑습니다"를 플레이 하게 됩니다.
    # 눈치 채셨을지 모르곘지만, discord.Status.online에서 online을 dnd로 바꾸면 "다른 용무 중", idle로 바꾸면 "자리 비움"으로 바뀝니다.
    await client.change_presence(status=discord.Status.online,
                                 activity=discord.Game("반갑습니다 :D"))
    print("I'm Ready!")  # I'm Ready! 문구를 출력합니다.
    print(client.user.name)  # 봇의 이름을 출력합니다.
    print(client.user.id)  # 봇의 Discord 고유 ID를 출력합니다.


@client.event
async def on_message(message):  # 메시지가 들어 올 때마다 가동되는 구문입니다.
    if message.author.bot:  # 채팅을 친 사람이 봇일 경우
        return None  # 반응하지 않고 구문을 종료합니다.
    if message.content == "시계":  # !명령어 라는 채팅을 친다면
        await message.channel.send(
            time.strftime('%Y-%m-%d %a %X', time.localtime(time.time()))
        )  # 메시지가 보내진 채널에 "응답"이라고 보냅니다


access_token = os.environ["BOT_TOKEN"]
Пример #14
0
import discord #모듈 불러오기
token = "My Bot Token" #봇 토큰 설정하기
client = discord.Client() #client 설정하기

@client.event
async def on_ready(): #봇이 준비되었을때
    print("봇 준비 완료!")
    print(client.user)
    print("============================")

@client.event
async def on_message(message): #사용자가 메세지를 입력했을때
    if message.content == "야": #만일 사용자가 "야" 라고 입력했을때
        await message.channel.send("왜") #봇이 "왜" 라고 답한다.
    if message.content == "ㅎㅇ": #만일 사용자가 "야" 라고 입력했을때
        await message.channel.send("ㅂㅇ") #봇이 "왜" 라고 답한다.
    
    if message.content == "임베드내놔":
        embed = discord.Embed(timestamp=message.created_at, colour=discord.Colour.red(), title="제-목", description="설-명")
        embed.set_thumbnail(url="https://prforest.ga/files/img/홍보숲.png")
        embed.set_image(url="https://postfiles.pstatic.net/MjAyMDA1MTVfNTcg/MDAxNTg5NTI0NzU1Nzcx.uK7HkqM-NEgBHLafECr0IfeftNM2RfmrkM-oq8q5KA0g.ZruZd3GTvpc2v-ei-PdJKxFleQMvLDUCNeoHSEGR8bMg.PNG.samsunghappytree123/%EA%B0%95%EC%9D%982.PNG?type=w773")
        embed.set_footer(text=message.author, icon_url=message.author.avatar_url)
        embed.add_field(name="필트 제목", value="필드 설명", inline=False) #inline이 False라면 다음줄로 넘깁니다.
        await message.channel.send(embed=embed)

client.run(token)
Пример #15
0
    print(f'Checking for git commit failed: {type(e).__name__} {e}')
    commit = '<unknown>'

try:
    branch = check_output(['git', 'rev-parse', '--abbrev-ref',
                           'HEAD']).decode()[:-1]
except CalledProcessError as e:
    print(f'Checking for git branch failed: {type(e).__name__} {e}')
    branch = '<unknown>'

print(f'Starting discord-mod-mail {version}!')

config = configparser.ConfigParser()
config.read('config.ini')

client = discord.Client(activity=discord.Game(name=config['Main']['playing']),
                        max_messages=100)
client.channel: discord.TextChannel

client.already_ready = False

client.last_id = 'uninitialized'

db = sqlite3.connect(DATABASE_FILE)
with db:
    if db.execute('PRAGMA user_version').fetchone()[0] == 0:
        print('Setting up', DATABASE_FILE)
        db.execute('PRAGMA application_id = 0x4D6F644D')  # ModM
        db.execute('PRAGMA user_version = 1')
        with open('schema.sql', 'r', encoding='utf-8') as f:
            db.executescript(f.read())
Пример #16
0
class Bot:
    class GuildInfo:
        def __init__(self, leading_user='', users_playing=[]):
            self.leading_user = leading_user
            self.users_playing = users_playing.copy()

        def __str__(self):
            return "LEAD: (" + str(self.leading_user) + "); " + str(
                list(map(lambda x: x.name, self.users_playing)))

        def __repr__(self):
            return "LEAD: (" + str(self.leading_user) + "); " + str(
                list(map(lambda x: x.name, self.users_playing)))

    class CommandHandler:
        def __init__(self, client):
            self.client = client
            self.commands = []

        def add_command(self, command):
            self.commands.append(command)

        def command_handler(self, message, dis_bot):
            for command in self.commands:
                if sum([
                        message.content.startswith(cm)
                        for cm in command['trigger']
                ]) > 0:
                    args = message.content.split(' ')
                    if args[0] in command['trigger']:
                        args.pop(0)
                        guild_id = message.guild.id
                        if command['args_num'] == 0:
                            return command['function'](dis_bot, message,
                                                       guild_id, self.client,
                                                       args)
                        else:
                            if len(args) >= command['args_num']:
                                return command['function'](dis_bot, message,
                                                           guild_id,
                                                           self.client, args)
                            else:
                                return [(Event.SEND, (
                                    message.channel,
                                    'command "{}" requires {} argument(s) "{}"'
                                    .format(command['trigger'],
                                            command['args_num'],
                                            ', '.join(command['args_name']))))]
                    else:
                        break

    guilds_inf = dict()
    discord_client = discord.Client()
    ch = CommandHandler(discord_client)

    # -----------------------CommandList--------------------------
    def commands_command(self, message, guild_id, client, args):
        try:
            count = 1
            command_list_str = '**Commands List**\n'
            for command in self.ch.commands:
                command_list_str += '{}) **{}** :\t {}\n\n'.format(
                    count, ', '.join([cm for cm in command['trigger']]),
                    command['description'])
                count += 1
            return Bot.default_channel_message(message, command_list_str)
        except Exception as e:
            print(e)

    ch.add_command({
        'trigger': ['!commands', '!cm'],
        'function': commands_command,
        'args_num': 0,
        'args_name': [],
        'description': 'Prints a list of all the commands!'
    })

    # ------------------------------------------------------------

    @staticmethod
    def default_channel_message(message, msg):
        return [(Event.SEND, (message.channel, msg))]

    def get_dict_roles(self, guild_id, auto=True, mas=[]):
        if auto:
            count_players = len(self.guilds_inf[guild_id].users_playing)
            if count_players < 6:
                return None
            elif count_players == 6:
                count_roles = {
                    'Мирный': 4,
                    'Мафия': 0,
                    'Дон мафии': 1,
                    'Комиссар': 1,
                    'Доктор': 0
                }
            else:
                maf = (count_players // 4) + 1
                wh = count_players - maf
                count_roles = {
                    'Мирный': wh - 2,
                    'Мафия': maf - 1,
                    'Дон мафии': 1,
                    'Комиссар': 1,
                    'Доктор': 1
                }
            return count_roles

        if len(mas) == 5:
            new_mas = list(map(int, mas))
            return {
                'Мирный': new_mas[0],
                'Мафия': new_mas[1],
                'Дон мафии': new_mas[2],
                'Комиссар': new_mas[3],
                'Доктор': new_mas[4]
            }

        return None

    def create_message_roles(self, dict_roles, guild_id):
        list_of_roles = []

        for key in dict_roles.keys():
            for i in range(dict_roles[key]):
                list_of_roles.append(key)

        users_roles = dict()
        i = 1
        while len(list_of_roles) != 0:
            random_index = random.randint(0, len(list_of_roles) - 1)
            users_roles[(i, self.guilds_inf[guild_id].users_playing[i - 1]
                         )] = list_of_roles[random_index]
            list_of_roles.pop(random_index)
            i += 1

        return_list = []
        leading_msg = ''
        for (index, user) in users_roles.keys():
            return_list.append((Event.SEND, (user, "{} - **{}**".format(
                user.mention, users_roles[(index, user)].upper()))))
            leading_msg += "{}) {} - **{}**\n".format(
                index, user.mention, users_roles[(index, user)].upper())
        return_list.append(
            (Event.SEND, (self.guilds_inf[guild_id].leading_user,
                          leading_msg)))

        return return_list

    # --------------------Hanging Roles Auto----------------------
    def hanging_roles_auto(self, message, guild_id, client, args):
        try:
            count = len(self.guilds_inf[guild_id].users_playing)
            if count < 6:
                return Bot.default_channel_message(
                    message,
                    "Минимальное количество игроков: 6\nНе хватает {} игроков".
                    format(6 - count))
            if self.guilds_inf[guild_id].leading_user == '':
                return Bot.default_channel_message(
                    message, "Выберите ведущего командой: !leading_me")

            dict_roles = self.get_dict_roles(guild_id=guild_id)

            if dict_roles is not None:
                msg = self.create_message_roles(dict_roles, guild_id)
                text = '**Роли выданы:**\n'
                for role, count in dict_roles.items():
                    if count > 0:
                        text += "**{}**: {};\n".format(role.upper(), count)
                msg.append((Event.SEND, (message.channel, text)))
                return msg
        except Exception as e:
            print(e)

    ch.add_command({
        'trigger': ['!start_auto', '!st_au'],
        'function': hanging_roles_auto,
        'args_num': 0,
        'args_name': [],
        'description': 'Starts auto handing out roles'
    })

    # ------------------------------------------------------------

    # --------------------Hanging Roles Not Auto------------------
    def hanging_roles_not_auto(self, message, guild_id, client, args):
        try:
            count = len(self.guilds_inf[guild_id].users_playing)
            if self.guilds_inf[guild_id].leading_user == '':
                return Bot.default_channel_message(
                    message, "Выберите ведущего командой: !leading_me")

            dict_roles = self.get_dict_roles(auto=False,
                                             mas=args,
                                             guild_id=guild_id)
            if dict_roles is not None:
                list_count = sum(list(map(int, args)))
                dif = abs(count - list_count)
                s = ''
                if list_count < count:
                    s = "Не верно введено кол-во ролей. Не хватает {} ролей игрокам" \
                        .format(dif)
                if list_count > count:
                    s = "Не верно введено кол-во ролей. Введено на {} ролей больше." \
                        .format(dif)
                if s != '':
                    return Bot.default_channel_message(message, s)

                msg = self.create_message_roles(dict_roles, guild_id)
                text = '**Роли выданы:**\n'
                for role, count in dict_roles.items():
                    if count > 0:
                        text += "**{}**: {};\n".format(role.upper(), count)
                msg.append((Event.SEND, (message.channel, text)))
                return msg

        except Exception as e:
            print(e)

    ch.add_command({
        'trigger': ['!start_not_auto', '!st_n_au'],
        'function':
        hanging_roles_not_auto,
        'args_num':
        5,
        'args_name': [
            '<кол-во мирных>', '<кол-во мафии>', '<наличие дона мафии 0/1>',
            '<наличие комиссара 0/1>', '<наличие доктора 0/1>'
        ],
        'description':
        'Starts handing out roles'
    })

    # ------------------------------------------------------------

    # --------------------Add leading user------------------------
    def add_leading_user(self, message, guild_id, client, args):
        try:
            user = message.author
            if user in self.guilds_inf[guild_id].users_playing:
                self.guilds_inf[guild_id].leading_user = user
                self.guilds_inf[guild_id].users_playing.remove(user)
                return Bot.default_channel_message(
                    message,
                    "{} is new leading user, but was removed from player list!"
                    .format(user.mention))
            elif user == self.guilds_inf[guild_id].leading_user:
                return Bot.default_channel_message(
                    message, "{} is already leading user!".format(
                        self.guilds_inf[guild_id].leading_user.mention))
            else:
                self.guilds_inf[guild_id].leading_user = user
                return Bot.default_channel_message(
                    message, "{} is new leading user".format(user.mention))
        except Exception as e:
            print(e)

    ch.add_command({
        'trigger': ['!leading_me', '!lm'],
        'function': add_leading_user,
        'args_num': 0,
        'args_name': [],
        'description': 'Adds leading user'
    })

    # ------------------------------------------------------------

    # --------------------Add player -----------------------------
    def add_player(self, message, guild_id, client, args):
        try:
            user = message.author
            if user == self.guilds_inf[guild_id].leading_user:
                self.guilds_inf[guild_id].users_playing.append(user)
                self.guilds_inf[guild_id].leading_user = ''

                return Bot.default_channel_message(
                    message,
                    "{} has been added to player list, but leading user has cleared"
                    .format(user.mention))
            elif user not in self.guilds_inf[guild_id].users_playing:
                self.guilds_inf[guild_id].users_playing.append(user)
                return Bot.default_channel_message(
                    message,
                    "{} has been added to player list".format(user.mention))
            else:
                return Bot.default_channel_message(
                    message, "{} is already added".format(user.mention))
        except Exception as e:
            print(e)

    ch.add_command({
        'trigger': ['!add_me', '!am'],
        'function': add_player,
        'args_num': 0,
        'args_name': [],
        'description': 'Adds author to player list'
    })

    # ------------------------------------------------------------

    # --------------------Remove player --------------------------
    def delete_player(self, message, guild_id, client, args):
        try:
            user = message.author
            if user not in self.guilds_inf[guild_id].users_playing:
                return Bot.default_channel_message(
                    message, "{} is not in the list.".format(user.mention))
            else:
                self.guilds_inf[guild_id].users_playing.remove(user)
                return Bot.default_channel_message(
                    message, "{} has been removed from player list".format(
                        user.mention))
        except Exception as e:
            print(e)

    ch.add_command({
        'trigger': ['!remove_me', '!rm'],
        'function': delete_player,
        'args_num': 0,
        'args_name': [],
        'description': 'Removes author to player list'
    })

    # ------------------------------------------------------------

    # --------------------Remove player by index -----------------
    def delete_player_by_index(self, message, guild_id, client, args):
        try:
            if len(self.guilds_inf[guild_id].users_playing) == 0:
                return Bot.default_channel_message(message,
                                                   "**List is empty!**")
            num = int(args[0])
            if num < 1 or num > len(self.guilds_inf[guild_id].users_playing):
                return Bot.default_channel_message(
                    message,
                    "**Wrong num** of player, you can use only 1-{} nums".
                    format(len(self.guilds_inf[guild_id].users_playing)))
            user = self.guilds_inf[guild_id].users_playing[num - 1]
            self.guilds_inf[guild_id].users_playing.remove(user)
            return Bot.default_channel_message(
                message,
                "{} has been removed from player list".format(user.mention))
        except Exception as e:
            print(e)

    ch.add_command({
        'trigger': ['!remove_index', '!ri'],
        'function': delete_player_by_index,
        'args_num': 1,
        'args_name': ['index_player'],
        'description': 'Removes player by index from list'
    })

    # ------------------------------------------------------------

    # --------------------Print list players ---------------------
    def print_list_players(self, message, guild_id, client, args):
        try:
            res = ''
            res += "Leading user is **{}**\n".format(
                "nobody " if self.guilds_inf[guild_id].leading_user ==
                '' else self.guilds_inf[guild_id].leading_user.name)
            if len(self.guilds_inf[guild_id].users_playing) == 0:
                res += "**Players List is empty**"
                return Bot.default_channel_message(message, res)
            users = '**Players List**\n'
            count = 1
            for user in self.guilds_inf[guild_id].users_playing:
                users += "{}) {}\n".format(count, user.name)
                count += 1
            return Bot.default_channel_message(message, res + users)
        except Exception as e:
            print(e)

    ch.add_command({
        'trigger': ['!list', '!l'],
        'function': print_list_players,
        'args_num': 0,
        'args_name': [],
        'description': 'Prints list of players of current game'
    })

    # ------------------------------------------------------------

    # --------------------Clear list players ---------------------
    def clear_list_players(self, message, guild_id, client, args):
        try:
            self.guilds_inf[guild_id].users_playing.clear()
            self.guilds_inf[guild_id].leading_user = ''
            return Bot.default_channel_message(
                message, "Players List has been cleared")
        except Exception as e:
            print(e)

    ch.add_command({
        'trigger': ['!clear_list', '!cll'],
        'function': clear_list_players,
        'args_num': 0,
        'args_name': [],
        'description': 'Clears list of players of current game'
    })

    # ------------------------------------------------------------

    # --------------------Clear leading user ---------------------
    def clear_leading(self, message, guild_id, client, args):
        try:
            self.guilds_inf[guild_id].leading_user = ''
            return Bot.default_channel_message(
                message, "Leading User has been cleared")
        except Exception as e:
            print(e)

    ch.add_command({
        'trigger': ['!clear_leading', '!cllead'],
        'function': clear_leading,
        'args_num': 0,
        'args_name': [],
        'description': 'Clears list of players of current game'
    })

    # ------------------------------------------------------------

    # --------------------Shuffle player list---------------------
    def shuffle_list(self, message, guild_id, client, args):
        try:
            random.shuffle(self.guilds_inf[guild_id].users_playing)
            return Bot.default_channel_message(message,
                                               "Players List has shuffled")
        except Exception as e:
            print(e)

    ch.add_command({
        'trigger': ['!shuffle', '!sh'],
        'function': shuffle_list,
        'args_num': 0,
        'args_name': [],
        'description': 'Shuffle player list'
    })

    # ------------------------------------------------------------

    # --------------------Rename users by game ---------------------
    def rename_players(self, message, guild_id, client, args):
        try:
            res_dict = dict()
            for i, user in enumerate(self.guilds_inf[guild_id].users_playing,
                                     1):
                res_dict[user] = "{:02d} {}".format(i, user.name)
            if self.guilds_inf[guild_id].leading_user != '':
                res_dict[self.guilds_inf[guild_id].leading_user] = \
                    "Ведущий {}".format(self.guilds_inf[guild_id].leading_user.name)
            return [(Event.RENAME, res_dict),
                    (Event.SEND, (message, 'Nicknames was changed'))]
        except Exception as e:
            print(e)

    ch.add_command({
        'trigger': ['!rename_all', '!r_all'],
        'function': rename_players,
        'args_num': 0,
        'args_name': [],
        'description': 'Rename all users by current game'
    })

    # ------------------------------------------------------------
    def start(self, token):
        self.discord_client.run(token)
Пример #17
0
 def __init__(self, bot_secret_key):
     self._client = discord.Client()
     self._bot_secret_key = bot_secret_key
                               textMessageDetails=dict(messageText=msg))))
    list_chatmessages_inset.execute()
    #print(list_chatmessages_inset.execute()) #debug for sending live chat messages


if __name__ == "__main__":
    args = argparser.parse_args()

    youtube = get_authenticated_service(
        args)  #authenticates the api and saves it to youtube
    getLiveId(youtube)

##discord portion of the bot
#this will be the main code

client = discord.Client(
)  #sets this to just client for reasons cuz y not? (didnt have to be done like this honestly could of been just running discord.Client().)


async def discordSendMsg(msg):  #this is for sending messages to discord
    global config
    global channelToUse  #pulls in t{0} : {1}".format(author,msg)he global variable
    await client.send_message(
        channelToUse,
        msg)  #sends the message to the channel specified in the beginning


@client.event
async def on_ready(
):  #when the discord api has logged in and is ready then this even is fired
    if firstRun == "off":
        #these 2 variables are used to keep track of what channel is thre real channel to use when sending messages to discord
Пример #19
0
#----------------------
import discord
from discord.ext import commands
import random
import sys
import string
import time
from time import sleep
import datetime
from countDown import countDown
from countDown import flamebotTimers

#---------------------
# BOT SETUP
TOKEN = 'X' # Sets the Bot token
client = discord.Client() # DO NOT CHANGE
prefix = '&' # Sets the Bot's Prefix
version = '3'

#---------------------
# CHECK FOR COMMANDS
#---------------------
@client.event
async def on_message(message):
    # Call to countdown timer to see if we need to trigger any alerts
    #flamebotTimers.poll()
    # we do not want the bot to reply to itself
    if message.author == client.user:
        return
    #------------------------#
    #    NEW COMMAND STYLE   #
Пример #20
0
from doctorMsg import *
from bossAlarmFunc import *
from userFunc import *

import discord
import asyncio
import os

print(discord.__version__)
# discord bot token
token = os.environ['BOT_TOKEN']

#discord client ref
app = discord.Client()

flag = False


# alram function
async def runAlram(message):
    global flag

    while flag:
        value = list_alramBossWeekdayIndex()
        await asyncio.sleep(value[0])
        userlist = list_getMentionUser()
        if len(userlist) > 0:
            menUser = ''
            for user in userlist:
                menUser += '<@' + str(user.id) + '> '
            await message.channel.send(menUser)
Пример #21
0
    def __init__(self, token, prefix='!'):
        # type: (str, str) -> None

        self.token = token
        self.prefix = prefix

        self.client = discord.Client()
        self.commands = OrderedDict()  # type: typing.Dict[str, DiscordBotCommand]

        @self.client.event
        async def on_message(message):
            # type: (discord.Message) -> None

            # Skip bot's own messages
            if message.author == self.client.user:
                return

            # Skip messages without a valid prefix
            if not message.content.startswith(self.prefix):
                return

            print(message.author.name, message.content)

            # Split message into command and payload
            message_in = message.content.strip().split(maxsplit=1)  # type: str
            command_in = message_in[0][len(self.prefix):]
            payload_in = '' if len(message_in) < 2 else message_in[1]

            if command_in not in self.commands:
                payload_out = 'The specified command was not found.'.format(command_in)

            elif len(payload_in) > DiscordBot.LENGTH_LIMIT:
                payload_out = 'Input message is too long.'

            else:
                command = self.commands[command_in]

                # Server-only commands
                if message.server is None and not command.can_run_direct:
                    payload_out = 'The specified command can be executed in servers only.'

                # Direct-only commands
                elif message.server is not None and not command.can_run_server:
                    payload_out = 'The specified command can be executed via direct messages only.'

                # Permission checking
                # TODO Implement permission checking outside of servers
                elif message.server is not None and \
                        not command.required_permissions.is_subset(message.author.server_permissions):
                    payload_out = 'You do not have permission to perform the specified command.'

                # When all checks passed, execute the command and retrieve the payload
                else:
                    if asyncio.iscoroutinefunction(command.function):
                        payload_out = await command.function(message, payload_in)
                    else:
                        payload_out = command.function(message, payload_in)

            if payload_out != '':
                # Mention user when running command in non-private channels
                if not message.channel.is_private:
                    payload_out = '<@{}> '.format(message.author.id) + payload_out

                # noinspection PyUnresolvedReferences
                await self.client.send_message(message.channel, payload_out)

        @self.client.event
        async def on_ready():
            print('Logged in as {}#{} (id {})'.format(
                self.client.user.name,
                self.client.user.discriminator,
                self.client.user.id
            ))
Пример #22
0
def main():
    with open('config.json') as f:
        client_id = json.load(f)['client_id']

    mm = None
    voice = None
    sound_map = {}

    client = discord.Client()

    @client.event
    async def on_ready():
        print('[yasumi]Logged in as {0.user}'.format(client))

    @client.event
    async def on_message(message):
        nonlocal mm
        nonlocal voice
        nonlocal sound_map

        if client.user != message.author:
            input_msg = message.content

            if input_msg == '/bye':
                await message.channel.send('[INFO]ごきげんよう')
                await client.close()
                sys.exit(0)

            elif input_msg.startswith('/yasumi init'):
                if input_msg == '/yasumi init':
                    mode = 'free'
                else:
                    mode, = parse('/yasumi init {}', input_msg).fixed
                try:
                    with open('config.json') as f:
                        conf = json.load(f)

                    sound_map = conf['sound']
                    mm = MessageManager(mode, conf)
                    channel = message.author.voice.channel
                    try:
                        voice = await channel.connect()
                    except ClientException:
                        print(
                            '[yasumi]Allready connected voice channel, continue.'
                            .format(client))
                        pass

                    await message.channel.send('[INFO]イニシャライズしたわ(システム: **' +
                                               mode + '**)')

                except ValueError as ve:
                    await message.channel.send('[INFO]登録されていないシステムよ: __' +
                                               mode + '__')
                except AttributeError as ae:
                    await message.channel.send('[INFO]適当なボイスチャンネルにログインして貰えるかしら'
                                               )

            elif input_msg.startswith('/yasumi help'):
                if mm is None:
                    await message.channel.send('[INFO]イニシャライズして頂戴')
                else:
                    if input_msg == '/yasumi help':
                        help_at = 'main'
                    else:
                        help_at, = parse('/yasumi help {}', input_msg).fixed
                    try:
                        help_msg = mm.help(help_at, sound_map)
                        await message.channel.send(help_msg)
                    except ValueError as ve:
                        await message.channel.send('[INFO]登録されていないシステムよ: __' +
                                                   help_at + '__')

            elif input_msg.startswith('/'):
                if mm is None:
                    await message.channel.send('[INFO]イニシャライズして頂戴')
                else:
                    player = str(message.author)
                    msg = mm(input_msg, player)

                    if isinstance(msg, str):
                        if not msg:
                            pass
                        else:
                            await message.channel.send(msg)

                    elif isinstance(msg, list):
                        for sub_msg in msg:
                            await message.channel.send(sub_msg[0],
                                                       file=sub_msg[1])
                            time.sleep(1.0)

                    elif isinstance(msg, tuple):
                        if isinstance(msg[1], discord.File):
                            await message.channel.send(msg[0], file=msg[1])
                        else:
                            if voice.is_playing():
                                voice.source = discord.FFmpegPCMAudio(
                                    mm.voice_path)
                            else:
                                voice.play(
                                    discord.FFmpegPCMAudio(mm.voice_path))
                            await message.channel.send(msg[0])

                    else:
                        await message.channel.send('[INFO]無効なコマンドよ: __' +
                                                   input_msg + '__')

            elif input_msg.startswith('#'):
                if not voice:
                    await message.channel.send('[INFO]イニシャライズして頂戴')
                elif voice.is_playing():
                    voice.source = discord.FFmpegPCMAudio(sound_map[input_msg])
                else:
                    try:
                        voice.play(discord.FFmpegPCMAudio(
                            sound_map[input_msg]))
                    except KeyError:
                        await message.channel.send('[INFO]登録されていないサウンドよ: __' +
                                                   input_msg + '__')
                    except TypeError:
                        await message.channel.send('[INFO]ファイルが正しい形式じゃないわね')

    client.run(client_id)
Пример #23
0
def main(dc_token, steam_key):
    """
    メインの関数

    Parameters
    ----------
    dc_token : str
        discordのBotのトークン
    steam_key : str
        steam API 接続用のKey
    """
    global setting
    client = discord.Client()

    @client.event
    async def on_ready():
        """
        Bot起動時に動作(通知機能)
        """
        pass

    @client.event
    async def on_message(message):
        global setting
        """
        メッセージが送られた時動作

        Parameters
        ----------
        message : str
            送られたメッセージ
        """

        # チャンネルがtext以外の場合(ボイスチャンネル、DM等)return
        if str(message.channel.type) != 'text':
            return

        # 設定ファイル内にサーバーIDがない場合追加
        if str(message.guild.id) not in setting:
            setting[str(message.guild.id)] = {}
            res = write_setting(setting)
            if res != STANDARD_RETURN.OK:
                print('[warn] first setting failed ' + str(message.guild.id))
                return

        # 会話系
        if str(client.user.id) in message.content:
            if random.randint(1, 100) > 98:
                await message.channel.send(f'{message.author.mention} ...')
                return
            talk_status = talk(message.content)

            # 非同期によって変数が反映されない?のが心配なので先にリストを作っておく
            talk_list_dt = [
                '二度とわたしに話しかけないで', '変態ね', 'セクハラよ', 'こんなことしてないで街づくりでもしたらどう?'
            ]
            talk_list_tsun = ['知ってる', '当然よね', '当たり前のこと言わないで', 'もっと言ってもいいのよ']
            talk_list_other = ['ん?', 'わからないわ']
            talk_list_ikigomi = ['あんたには負けないんだから', '気合十分よ', '今年も負けないからね']

            if talk_status == TALK_RETURN.DT:
                if message.author.id == org_master:
                    await message.channel.send(
                        f'{message.author.mention} 私を作ってくれたことは感謝してる。でも{random.choice(talk_list_dt)}'
                    )
                else:
                    await message.channel.send(
                        f'{message.author.mention} {random.choice(talk_list_dt)}'
                    )
            elif talk_status == TALK_RETURN.TSUN:
                await message.channel.send(
                    f'{message.author.mention} {random.choice(talk_list_tsun)}'
                )
            elif talk_status == TALK_RETURN.OTHER:
                await message.channel.send(
                    f'{message.author.mention} {random.choice(talk_list_other)}'
                )
            elif talk_status == TALK_RETURN.IKIGOMI:
                await message.channel.send(
                    f'{message.author.mention}  {random.choice(talk_list_ikigomi)}'
                )
            return

        # 各種設定
        elif message.content.startswith('r/set-gameid'):
            if message.author.id != server_admin and message.author.id != message.guild.owner_id:
                return
            try:
                setting[str(message.guild.id)]['gameid'] = str(
                    int(message.content.split(' ')[1]))
                write_setting(setting)
                await message.channel.send('[OK] gameid = ' +
                                           str(message.content.split(' ')[1]))
                return
            except:
                traceback.print_exc()
                await message.channel.send('[FAIL] gameid = ???')
                return

        # ヘルプを表示
        elif message.content == ('r/help'):
            embed = discord.Embed()
            embed.add_field(name='s/ word',
                            value='search on steam/steamを検索します',
                            inline=False)
            embed.add_field(name='r/help', value='ヘルプを表示します', inline=False)
            # 管理者だった場合以下も表示
            if message.author.id == server_admin or message.author.id == message.guild.owner_id:
                embed.add_field(
                    name='r/set-gameid',
                    value=
                    'You can get gameid on url of storepage. e.g.(Cities:Skylines) r/set-gameid 255710',
                    inline=False)
            embed.set_footer(text='Reika ver ' + str(__version__))
            await message.channel.send(embed=embed)
            return

        # 検索機能
        elif message.content.startswith('s/'):
            raw_searchtext = message.content.split(' ')
            if len(raw_searchtext) == 1:
                return
            search_word = []
            for i in range(1, len(raw_searchtext)):
                search_word.append(raw_searchtext[i])
            try:
                app_id = setting[str(message.guild.id)]['gameid']
            except:
                await message.channel.send(
                    '`r/set-gameid`コマンドを使用してゲームIDをセットしてください。')
                return
            ret, res = searchitem(search_word, steam_key, app_id)
            if ret != STANDARD_RETURN.OK:
                await message.channel.send('何も見つからなかった...')
                return
            embed = discord.Embed(title=res['title'],
                                  url=res['url'],
                                  description=res['description'],
                                  timestamp=res['timestamp'])
            embed.set_author(url=res['author']['url'],
                             name=res['author']['name'],
                             icon_url=res['author']['icon_url'])
            embed.set_thumbnail(url=res['thumbnail'])
            for i in range(1, len(res['field']) + 1):
                embed.add_field(name=res['field']['field' + str(i)]['name'],
                                value=res['field']['field' + str(i)]['value'],
                                inline=res['field']['field' +
                                                    str(i)]['inline'])
            embed.set_footer(text=res['footer'])
            await message.channel.send(embed=embed)
            return

        message_text = message.content
        for i in message.raw_mentions:
            message_text = message_text.replace('<@' + str(i) + '>',
                                                '<@' + str(i) + '> ')
        message_text = message_text.replace('\n', ' ').replace(' ',
                                                               ' ').split(' ')
        for i in message_text:
            url = re.fullmatch(
                r'https://steamcommunity.com/((sharedfiles)|(workshop))/filedetails/\?id=[0-9]+.*',
                i)
            if url:
                ret, res = get_contentdetail(
                    str(
                        int(
                            urllib.parse.parse_qs(
                                urllib.parse.urlparse(
                                    url.group()).query)['id'][0])), steam_key)
                if ret != STANDARD_RETURN.OK:
                    raise Exception
                embed = discord.Embed(title=res['title'],
                                      url=res['url'],
                                      description=res['description'],
                                      timestamp=res['timestamp'])
                embed.set_author(url=res['author']['url'],
                                 name=res['author']['name'],
                                 icon_url=res['author']['icon_url'])
                embed.set_thumbnail(url=res['thumbnail'])
                for i in range(1, len(res['field']) + 1):
                    embed.add_field(
                        name=res['field']['field' + str(i)]['name'],
                        value=res['field']['field' + str(i)]['value'],
                        inline=res['field']['field' + str(i)]['inline'])
                embed.set_footer(text=res['footer'])
                await message.channel.send(embed=embed)

    client.run(dc_token)
Пример #24
0
import discord
import requests
from colorama import Fore
from colored import fg, attr
class colors:
    red = fg('#ff004d8')
    reset = attr('reset')
    gray = fg('#ff4b00')
    gray = fg('#ff4b00')
TOKEN = "ODMyMjI0MDU4ODM3ODI3NTg0.YHgrDQ.fDGDj9oFnkbLyMeemArMYH1ANdA"
client = discord.Client(intents=discord.Intents.all())
print(f'''
                                             {Fore.LIGHTBLACK_EX}█████{colors.gray}╗ {Fore.LIGHTBLACK_EX}██████{colors.gray}╗  {Fore.LIGHTBLACK_EX}██████{colors.gray}╗  {Fore.LIGHTBLACK_EX}██████{colors.gray}╗ 
                                            {Fore.LIGHTBLACK_EX}██{colors.gray}╔══{Fore.LIGHTBLACK_EX}██{colors.gray}╗╚════{Fore.LIGHTBLACK_EX}██{colors.gray}╗{Fore.LIGHTBLACK_EX}██{colors.gray}╔═{Fore.LIGHTBLACK_EX}████{colors.gray}╗{Fore.LIGHTBLACK_EX}██{colors.gray}╔═{Fore.LIGHTBLACK_EX}████{colors.gray}╗
                                            {Fore.LIGHTBLACK_EX}{colors.gray}╚{Fore.LIGHTBLACK_EX}█████{colors.gray}╔╝{Fore.LIGHTBLACK_EX} █████{colors.gray}╔╝{Fore.LIGHTBLACK_EX}██{colors.gray}║{Fore.LIGHTBLACK_EX}██{colors.gray}╔{Fore.LIGHTBLACK_EX}██{colors.gray}║{Fore.LIGHTBLACK_EX}██{colors.gray}║{Fore.LIGHTBLACK_EX}██{colors.gray}╔{Fore.LIGHTBLACK_EX}██{colors.gray}║
                                            {Fore.LIGHTBLACK_EX}{Fore.LIGHTBLACK_EX}██{colors.gray}╔══{Fore.LIGHTBLACK_EX}██{colors.gray}╗ ╚═══{Fore.LIGHTBLACK_EX}██{colors.gray}╗{Fore.LIGHTBLACK_EX}████{colors.gray}╔╝{Fore.LIGHTBLACK_EX}██{colors.gray}║{Fore.LIGHTBLACK_EX}████{colors.gray}╔╝{Fore.LIGHTBLACK_EX}██{colors.gray}║
                                            {Fore.LIGHTBLACK_EX}{colors.gray}╚{Fore.LIGHTBLACK_EX}█████{colors.gray}╔╝{Fore.LIGHTBLACK_EX}██████{colors.gray}╔╝╚{Fore.LIGHTBLACK_EX}██████{colors.gray}╔╝╚{Fore.LIGHTBLACK_EX}██████{colors.gray}╔╝
                                             {colors.gray}╚════╝ ╚═════╝  ╚═════╝  ╚═════╝ 
                                       ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 
                                         ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━  
''')
@client.event
async def on_connect():
   ask = int(input("server id: "))
   msg = input("what u wanna say?: ")
   guild = client.get_guild(ask)
   session = requests.Session()
   for member in guild.members:
      try:
        data = await member.create_dm()
        r = session.post(f"https://discord.com/api/v8/channels/{data.id}/messages", json={'content': f'{data.recipient.mention} '+msg}, headers={'Authorization': f'Bot {TOKEN}'})
Пример #25
0
import discord
import ids
import chess as chs
import assets as ass
import visualizer as viz
import random
import base64

intents = discord.Intents(messages=True, members=True, guilds=True)
client = discord.Client(intents=intents)

channelIds = ids.channelIds
clientKey = ids.clientKey

nextGameCounter = 99999999999

finishedGames = []
ongoingGames = []
gameAwaitingPlayers = []


@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))


@client.event
async def on_message(message):
    channelId = message.channel.id
    if message.author == client.user or channelId not in channelIds:
        return
Пример #26
0
#!/c/Users/SU/AppData/Local/Programs/Python/Python38/python
# THIS IS IN PYTHON 3!!!
# Path: ~/AppData/Local/Programs

import traceback
import os
import discord
import sys
import asyncio
import json

client = discord.Client(fetch_offline_members=True)


@client.event
async def on_ready():
    debug('We have logged in as {0.user}'.format(client))


def role_exists(guild, role):
    for r in guild.roles:
        if str(r) == role:
            return True
    return False


def f1(r, name):
    debug("f1: " + str(r))
    return r.name == name

Пример #27
0
import discord
from discord.ext.commands import bot
from discord import game
from discord.ext import commands
import asyncio
import platform
import colorsys
import random
import time

client = commands.Bot(command_prefix = '!', case_insensitive=True)
Client = discord.client
Clientdiscord = discord.Client()

@client.event
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('--------')
    print('Created by niloj')

@client.command(pass_context = True)
@commands.has_permissions(kick_members=True)     
async def userinfo(ctx, user: discord.Member):
    r, g, b = tuple(int(x * 255) for x in colorsys.hsv_to_rgb(random.random(), 1, 1))
    embed = discord.Embed(title="{}'s info".format(user.name), description="Here's what I could find.", color = discord.Color((r << 16) + (g << 8) + b))
    embed.add_field(name="Name", value=user.name, inline=True)
    embed.add_field(name="ID", value=user.id, inline=True)
    embed.add_field(name="Status", value=user.status, inline=True)
    embed.add_field(name="Highest role", value=user.top_role)
    embed.add_field(name="Joined", value=user.joined_at)
Пример #28
0
      '    Target URL: ' + analyzer.FFLOGS_DPS_URL.format(
          report_id=report_id, boss_id=analyzer.FFLOGS_TARGET_BOSS_ID) + '\n'
      '###################################\n')

result_text = analyzer.get_analysys_result(
    config.get('DEFAULT', 'FFLOGS_API_KEY'), report_id)

# 分析結果出力
if client is None:
    print('###################################\n'
          ' Results\n'
          '###################################\n')
    print(result_text)

else:
    client = discord.Client(loop=asyncio.new_event_loop())

    @client.event
    async def on_ready():
        if not client.is_ready():
            return

        channel = client.get_channel(
            int(config.get('DEFAULT', 'DISCORD_CHANNEL_ID')))
        embed = discord.Embed(title='Analysis completed.',
                              url=analyzer.FFLOGS_DPS_URL.format(
                                  report_id=report_id,
                                  boss_id=analyzer.FFLOGS_TARGET_BOSS_ID),
                              color=0x7cfc00)
        embed.add_field(name='Result', value=result_text)
Пример #29
0
import time
from gtts import gTTS
from tempfile import NamedTemporaryFile
import os
import pickle
import cowsay
import urllib.request
import requests
from bs4 import BeautifulSoup
from shutil import copyfile
import datetime
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plot

client = discord.Client()

player_lock = asyncio.Lock()
tts_lock = asyncio.Lock()

enabled = True
message_channel = None
admin_channel = None
tts_flag = False
use_avconv = True

nicknames = {}
blacklist = []

helpmsg = """ COMMAND LIST:
>!bbhelp / !bb    -    Display help message
Пример #30
0
              osascript -e 'display notification "{}" with title "{}"'
              """.format(message, title))

def read_pokemon_info(data):
    message = ""
    if read_pokemon_name:
        message = data['name']
    if read_pokemon_level:
        if data['level'] == 35:
            message = "{} max level".format(message)
        else:
            message = "{} evel {}".format(message, data['level'])
    os.system("say {}".format(message))

# Bot
c = discord.Client()

@c.event
async def on_ready():
    welcome = "Logged in as {0.name} - {0.id}\n".format(c.user)
    # Make the log bot appear offline.
    await c.change_presence(status=discord.Status.invisible)
    print(welcome)

@c.event
async def on_message(message):
    channel = "{}".format(message.channel.id)
    if channel in accept_channels:
        parse_message(message)

def parse_message(message):