Exemplo n.º 1
0
import subprocess as sub  # needed for softreload to pull from git kekw
import handler  #handle all incoming msgs
from discord.ext.commands import Bot
import loophandler as loop

logger = logging.getLogger("botlogger")

FALLBACK_PREFIX = "°"

with open(".token.txt") as t_file:
    TOKEN = t_file.read()

STARTTIME = datetime.now()

client = Bot(
    FALLBACK_PREFIX
)  #not using these parts of the discord library, so doesn't matter what prefix is given to the bot instance
handler.init(client, STARTTIME)


@client.event
async def on_ready():
    handler.ISRELOADING = False
    loop.init(client, handler_ref=handler)
    print(f'[bot.py] {client.user} has connected')
    logger.info("Bot Online")


@client.event
async def on_message(message: discord.Message):
    handling_code = await handler.handle(message)
Exemplo n.º 2
0
from discord.ext.commands import Bot

from Token import TokenDiscord

tokenDiscord = TokenDiscord()

bot = Bot(command_prefix="<3", help_command=None)

@bot.event
async def on_ready(self):
    print(f'Logged on as {self.user}!')

bot.load_extension("Commands")

bot.run(tokenDiscord.uploadToken()['token'])
Exemplo n.º 3
0
import discord
from discord.ext.commands import Bot
import random

Super_idol = Bot(command_prefix='s!')
command_list = {'hello', 'flip'}

master = [
    'Hello master <3', 'I love you master,'
    ' you are the best', 'Awww master talked to me >///<',
    'How was your day master?'
]

pleb = [
    'I am not talking to plebs', 'You are not my master, don\'t talk to me',
    'F**k off'
]


@Super_idol.event
async def on_ready():
    print('Logged in as')
    print(Super_idol.user.id)
    print(Super_idol.user.name)
    print('--------------------')

    game = discord.Game()
    game.name = f"Type s!help for help."
    await Super_idol.change_presence(game=game)

Exemplo n.º 4
0
from models.weapon import Weapon
from models.events import Event
from utils.config import Config
from utils.parsing import convert_ISO_date_to_string, convert_args_to_dict

config = Config("config.ini")
channel = None
active_messages = {}
emoji_reactions = {
    "adv": config.adv_reactions,
    "wyr": config.wyr_reactions,
    "dra": config.dra_reactions,
    "wep": config.wep_reactions
}
mana_spiral_reaction = config.mana_spiral
client = Bot(command_prefix=config.command_start)


def start_discord_bot():
    client.run(config.token)


# region Reaction Processing
def process_adventurers_reaction(emoji, adv):
    if emoji == "\U0001F5BC":  # Full picture
        return create_dynamic_portrait_embed(adv, "adventurers/full")
    # Fixes an issue where non-spiralled units could get a megaphone reaction
    if adv.manaspiral == 1:
        level = get_level(emoji, True)
    else:
        level = get_level(emoji)
Exemplo n.º 5
0
__version__ = "1.0"

#---#

import discord
from discord.ext.commands import Bot

from asyncio import sleep
from json import load
from os.path import dirname
from random import randint
from re import findall

#-----#

Bot = Bot(command_prefix=">")
Bot.remove_command("help")

#-----#

Channel = load(open(r"{0}\config.json".format(dirname(__file__))))["ChannelID"]
User = load(open(r"{0}\config.json".format(dirname(__file__))))["UserID"]

#-----#

@Bot.event
async def on_ready():
	print("{0}\n<< Ready >>\n{0}\nLogged in as: {1}\nID: {2}\n{0}".format("-"*5, str(Bot.user.name).encode(), str(Bot.user.id)))
	
	# - Daily Credits - #
	
Exemplo n.º 6
0
import os
import smtplib

from discord import FFmpegPCMAudio
from discord.ext import commands
from discord.ext.commands import Bot
from dotenv import load_dotenv

load_dotenv()

client = Bot("-")


@client.event
async def on_ready():
    print('Music Bot Ready')


@client.command(aliases=['p', 'pl'])
async def play(ctx,
               url: str = 'https://nr3.newradio.it/proxy/omnianet?mp=/stream'):
    channel = ctx.message.author.voice.channel
    player = ctx.message.author

    try:
        voice = await channel.connect()
    except:
        pass

    source = FFmpegPCMAudio(
        executable="C:/Users/Luca/Documents/nn/trp/bin/ffmpeg.exe", source=url)
Exemplo n.º 7
0

def getConfig(path):
    configFile = open(path, "r")
    return json.loads(configFile.read())


config = getConfig("config.json")

# Preparing the cogs
initial_extensions = ['Airhorn', 'Basics', 'Fun']

# Prefix, description that appear in !help
client = Bot(
    description=
    "dooting on the haters | The Soundboard | 1 in 100 chance to be rickrolled for free when using bot!",
    command_prefix=config['prefix'],
    pm_help=False)

# Loading special extension for Eval
client.load_extension('jishaku')


# Initialization of bot and logging in
@client.event
async def on_ready():
    # We setup the logger first
    Logger.setup_logger()

    await Logger.log(
        "Bot startup done!", client, "INFO",
Exemplo n.º 8
0
#Dependencies: discord.py API, PyDictionary, youtube_dl, discord.py[voice]

#Type @help in Discord chat for list of commands

import discord
import random
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
from PyDictionary import PyDictionary as PyDict
import time
from datetime import datetime
import math

TOKEN = "NTY0NTA0NTI0MjgzNDQ1MjQ4.XKo7RQ.FfRfJOUyoCk1JuV90htORUQ_XBg"
clientBot = Bot('@')
clientBot.remove_command('help')

pydict = PyDict()
players = {}


#Bot event handlers
@clientBot.event
async def on_ready():  #signals successful connection
    print("Logged in as")
    print(clientBot.user.name)
    print(clientBot.user.id)


@clientBot.event
Exemplo n.º 9
0
# bot.py
import os
import random
import discord
import discord.ext
from discord.ext import commands
from discord.ext.commands import Bot

client = discord.Client()
bot = Bot('.')

client = commands.Bot(command_prefix='.')

import dotenv
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')


@client.event
async def on_ready():
    print(f'{client.user.name} has connected to Discord!')


@client.event
async def on_member_join(member):
    await member.create_dm()
    await member.dm_channel.send(
        f'Yo F****r {member.name}, This my Discord Server my name is f****n johnny and respect dat!'
    )
Exemplo n.º 10
0
import discord
from discord.ext.commands import Bot
from datetime import datetime

bot = Bot(command_prefix = "?")

@bot.event
async def on_ready():
    print('Ready')

@bot.command(name='record',
                description='records all songs played and saves to a file',
                brief='RECORD',
                aliases=['rec'])
async def record(ctx):
    recording = 1

    chan = ctx.channel

    now = datetime.now()
    now = now.strftime('%m-%d-%Y_%H-%M-%S')
    fileName = 'DiscordRecord/'+ str(now) + '.txt'

    f = open(fileName,'w+')

    await ctx.send('Recording all song requests from this channel')
    chat = await getInput(chan)
    while recording:
        if chat.startswith('-play') or chat.startswith('!play'):
            f.write(chat[6:] + '\n')
            await ctx.send('Recorded')
Exemplo n.º 11
0
handler.setFormatter(
    logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)

debug_logger = logging.getLogger('discord')
debug_logger.setLevel(logging.DEBUG)
debug_handler = logging.FileHandler(filename=abspath(
    dirname(abspath(__file__)) + '/../logs/discord_debug.log'),
                                    encoding='utf-8',
                                    mode='w')
debug_handler.setFormatter(
    logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
debug_logger.addHandler(debug_handler)

bot = Bot(command_prefix='>>',
          command_not_found='No command named {0} found.',
          description='Current Conditions & Forecast',
          pm_help=True)


@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')


@bot.command(
    enabled=True,
    pass_context=True,
)
Exemplo n.º 12
0
#!/usr/bin/python3

# These are the dependecies. The bot depends on these to function, hence the name. Please do not change these unless your adding to them, because they can break the bot.

import discord
from discord.ext.commands import Bot
from discord.ext import commands
import platform
from functions import *

# Here you can modify the bot's prefix and description and wether it sends help in direct messages or not.
client = Bot(description="Basic Bot by Habchy#1665",
             command_prefix="-fgc ",
             pm_help=False)

# This is what happens everytime the bot launches. In this case, it prints information like server count, user count the bot is connected to, and the bot id in the console.
# Do not mess with it because the bot can break, if you wish to do so, please consult me or someone trusted.


@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('Current Discord.py Version: {} | Current Python Version: {}'.format(
        discord.__version__, platform.python_version()))
    print('--------')
    print('Use this link to invite {}:'.format(client.user.name))
    print(
Exemplo n.º 13
0
    console_log.setLevel(
        logging.DEBUG)  # log levels to be shown at the console
    file_log = logging.FileHandler(logfile)
    file_log.setLevel(logging.DEBUG)  # log levels to be written to file
    formatter = logging.Formatter(
        '{asctime} - {name} - {levelname} - {message}', style='{')
    console_log.setFormatter(formatter)
    file_log.setFormatter(formatter)
    logger.addHandler(console_log)
    logger.addHandler(file_log)
    return logger


log = setup_logger()
bot = Bot(activity=Activity(name='.help | D&D 5e', type=ActivityType.watching),
          command_prefix=prefix,
          pm_help=True)

bot.start_time = datetime.datetime.now()


@bot.event
async def on_ready():
    log.info(f"Connected as {bot.user}, using discord.py {discver}")


def main():
    """Load cogs, configuration, and start the bot."""
    for extension in startup_extensions:
        try:
            log.debug(f'Loading extension: {extension}')
Exemplo n.º 14
0
import random
from discord.ext.commands import Bot
from discord.utils import find
import EightSpeaks as ES

#logging
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='discord.log',
                              encoding='utf-8',
                              mode='w')
handler.setFormatter(
    logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)

eight = Bot(command_prefix="/")  #Eightbot


@eight.event
async def on_message(message):
    if message.author == eight.user:
        return  #stops him responding to himself

    #TODO: Stop him spamming
    #elif message.content.startswith('o/'):
    #    await eight.send_message(message.channel, '\o') #waves back
    #    await asyncio.sleep(60)

    #elif 'o7' in message.content:
    #    await eight.send_message(message.channel, 'o7') #salutes
    #    await asyncio.sleep(60)
Exemplo n.º 15
0
from src.tastybot import TastyBot
from src.tastylisten import TastyListen
from src.create_db import create_csv

if len(sys.argv) > 1:
    if '--help' in sys.argv or '-h' in sys.argv:
        print('Help for TastyBot:')
        print(f'\tpython3 {sys.argv[0]}: start the TastyBot')
        print(f'\tpython3 {sys.argv[0]} --init: create the database file')
        print(f'\tpython3 {sys.argv[0]} --help: print this help message')
        sys.exit(0)

    if '--init' == sys.argv[1] and len(sys.argv) == 2:
        create_csv('songs', 'songs.csv')
        print('DB created.')
        sys.exit(0)

    print('Error when parsing arguments.')
    print('Use --help.')
    sys.exit(1)

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
PREFIX = '!'
SPLIT_TOKEN = '::'

bot = Bot(command_prefix=PREFIX)
bot.add_cog(TastyBot(bot))
bot.add_cog(TastyListen(bot))
bot.run(TOKEN)
Exemplo n.º 16
0
async def findMessage(channel, reqdtitle):
    async for message in channel.history(limit=300):
        if message.author == bot.user:
            if message.embeds[0].title == reqdtitle:
                return message
            else:
                requestedMessage = 'Null'
        else:
            requestedMessage = 'Null'
    return requestedMessage


print(discord.__version__)
token, identifier, channellist = initialize()
bot = Bot(identifier, description='')


@bot.event
async def on_ready():
    print('Logged in as:')
    print(bot.user.name)
    print(bot.user.id)
    print('\nPress Ctrl + C to exit')


@bot.command(pass_context=True)
async def say(ctx, *, message: str):
    if str(ctx.message.channel.id) in channellist:
        await ctx.send(message)
Exemplo n.º 17
0
Arquivo: bot.py Projeto: ethanpp/kek
intents.guilds = True
intents.emojis = True
intents.bans = True
intents.guild_typing = False
intents.typing = False
intents.dm_messages = False
intents.dm_reactions = False
intents.dm_typing = False
intents.guild_messages = True
intents.guild_reactions = True
intents.integrations = True
intents.invites = True
intents.voice_states = False
intents.webhooks = False

bot = Bot(command_prefix=config.BOT_PREFIX, intents=intents)


# The code in this even is executed when the bot is ready
@bot.event
async def on_ready():
    bot.loop.create_task(status_task())
    print(f"Logged in as {bot.user.name}")
    print(f"Discord.py API version: {discord.__version__}")
    print(f"Python version: {platform.python_version()}")
    print(f"Running on: {platform.system()} {platform.release()} ({os.name})")
    print("-------------------")


# Setup the game status task of the bot
async def status_task():
Exemplo n.º 18
0
import discord
import asyncio
from discord.ext.commands import Bot, CommandNotFound

from commands import basic_commands
info = "```This Bot was created by Kevin Good using Python with the discord.py API```"
#allows the bot to access these types of data
intents = discord.Intents.default()
intents.members = True
intents.guilds = True
intents.bans = True
intents.messages = True
file = open('secret_token.txt', 'r')
token = file.readline().rstrip()
bot = Bot(command_prefix="!", description=info, intents=intents)
bot.add_cog(basic_commands(Bot))


#when the bot has finished logging in & connecting, display a greeting message to
#all servers it is currently in.
@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')
    #a guild is the discord terminology for a server
    #list servers the bot is a part of in command prompt
    for server in bot.guilds:
        print(server.name)
        await server.channels[0].send("KevinBot is online. Type !help for list of commands")
Exemplo n.º 19
0
import discord
from discord.ext.commands import Bot
from discord.ext import commands
from discord.ext.commands.cooldowns import BucketType
import asyncio
import platform
import colorsys
import random
import os
import time
from discord.voice_client import VoiceClient
from discord import Game, Embed, Color, Status, ChannelType


Forbidden= discord.Embed(title="Permission Denied", description="1) Please check whether you have permission to perform this action or not. \n2) Please check whether my role has permission to perform this action in this channel or not. \n3) Please check my role position.", color=0x00ff00)
client = Bot(description="DarkBot Bot is best", command_prefix="d!", pm_help = True)
client.remove_command('help')


async def status_task():
    while True:
        await client.change_presence(game=discord.Game(name='for d!help'))
        await asyncio.sleep(5)
        await client.change_presence(game=discord.Game(name='with '+str(len(set(client.get_all_members())))+' users'))
        await asyncio.sleep(5)
        await client.change_presence(game=discord.Game(name='in '+str(len(client.servers))+' servers'))
        await asyncio.sleep(5)
        

	
@client.event
Exemplo n.º 20
0
import discord
from discord.ext.commands import Bot

from info import Info
from lobby import Lobby
from options import Options
from room import RoomError
from rooms import ROOMS, MissingChannelError
from round import Round
from shibboleth import GameActionError, GameInitializationError
from status import Status
from help import CommandError

BOT_PREFIX = "!"
bot = Bot(command_prefix=BOT_PREFIX, case_insensitive=True)
bot.remove_command("help")

COGS = [Lobby(bot), Round(bot), Info(bot), Options(bot), Status(bot)]

for cog in COGS:
    bot.add_cog(cog)


@bot.event
async def on_message_edit(_before, after):
    await bot.process_commands(after)


@bot.event
async def on_command_error(ctx, exception):
Exemplo n.º 21
0
import discord
from discord import Member, Role, Embed
from discord.message import Message
from discord.ext import commands
from discord.ext.commands import Bot, Context, Group

from nachomemes import Configuration, SimpleCache, Uploader
from nachomemes.template import TemplateError
from nachomemes.guild_config import GuildConfig
from nachomemes.store import Store, TemplateEncoder, update_serialization

# this description describes
DESCRIPTION = "A bot to generate custom memes using pre-loaded templates."

# this is the bot
bot = Bot(command_prefix="!", description=DESCRIPTION)

# this is where we keep the memes
STORE: Store

UPLOADER: Uploader

# Base directory from which paths should extend.
BASE_DIR = Path(__file__).parent.parent

# Debug mode (true or false)
DEBUG = False

UPLOAD_ALL = True

# recent meme requests (and the resulting meme message)
Exemplo n.º 22
0
def reloadMusicList(ctx):
    msList = os.listdir(config.MUSPATH)
    sourcesList = [[], msList, 'None']
    for i in msList:
        if i[-4:] != '.mp3':
            msList.remove(i)
    for j in msList:
        sourcesList[0].append(discord.FFmpegPCMAudio(config.MUSPATH + j))
        if len(sourcesList[0]) >= 9:
            break
    serverPlayList[ctx.guild.id] = sourcesList



bot = Bot(command_prefix='!')


def addNewTrack(ctx):
    for i in serverPlayList[ctx.guild.id][1]:
        serverPlayList[ctx.guild.id][0].append(discord.FFmpegPCMAudio(config.MUSPATH + i))
        if len(serverPlayList[ctx.guild.id][0]) >= 9:
            break


def nextSound(ctx):
    vc = ctx.message.guild.voice_client
    #vc.play(serverPlayList[ctx.guild.id][0]), after=lambda e: nextSound(ctx)
    vc.play(serverPlayList[ctx.guild.id][0][0], after=lambda e: nextSound(ctx))
    serverPlayList[ctx.guild.id][0].pop(0)
    serverPlayList[ctx.guild.id][2] = serverPlayList[ctx.guild.id][1].pop(0)
Exemplo n.º 23
0
from discord.ext.commands import Bot
import bot.models
from bot.config import config

client = Bot(command_prefix=config["BOT_PREFIX"], case_insensitive=True)
chat_bot = bot.models.ChatBot(config["MINIMUM_CONFIDENCE"], config["MAXIMUM_CONFIDENCE"])

from bot import events, commands
Exemplo n.º 24
0
import os
import discord
from discord.ext.commands import Bot

client = Bot(command_prefix="[]")
client.load_extension('cogs.role')
client.remove_command('help')


@client.event
async def on_ready():
    print("session started")
    await client.change_presence(activity=discord.Game(name="Billy's Basement GameJam 2021"))


@client.command(name="ping", aliases=["pong"])
async def ping(ctx):
    await ctx.send(client.latency)


client.run(os.getenv('DISCORD_TOKEN'))
Exemplo n.º 25
0
import os
import shutil
import glob
import json
from random import *
from random import choice
from PickerNUploader import PickerAndUploader, NoFilesInDropboxError
from threading import Thread
from Config import *

# Now it's time to import discord and do the weed stuff
import discord
import asyncio
from discord.ext import commands
from discord.ext.commands import Bot
client = Bot(command_prefix=["w", "W"])
speed = 0.10  # how fast will it edit the message


# for web server (route /bot or /invite)
def bot_id():
    return client.user.id


# delete pictures every {} minutes
async def delete_media():
    time_in_min = 60 * 5
    while True:
        try:
            print("== Removing upload-media (looping task) ==")
            shutil.rmtree('upload-media/')
Exemplo n.º 26
0
    @classmethod
    async def from_url(cls, url, *, loop=None, stream=False):
        loop = loop or asyncio.get_event_loop()
        data = await loop.run_in_executor(
            None, lambda: ytdl.extract_info(url, download=not stream))

        if 'entries' in data:
            # take first item from a playlist
            data = data['entries'][0]

        filename = data['url'] if stream else ytdl.prepare_filename(data)
        return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options),
                   data=data)


bot = Bot(os.getenv('COMMAND_PREFIX'))

##############
### Events ###
##############


@bot.event
async def on_ready():
    logging.info('Discord Bot ready')


###########
## Music ##
###########
class Music(commands.Cog):
Exemplo n.º 27
0
import random
import asyncio
import aiohttp
import json
from discord import Game
from discord.ext.commands import Bot

BOT_PREFIX = ("=")
TOKEN = "NDcwNjE1NjY0NDUzODc3NzYw.DjZUhw.zwxQnStXOJPZ1zIGIt7Qyy_XPh0"  # Get at discordapp.com/developers/applications/me

client = Bot(command_prefix=BOT_PREFIX)


@client.command(name='8ball',
                description="Answers a yes/no question.",
                brief="Answers from the beyond.",
                aliases=['eight_ball', 'eightball', '8-ball'],
                pass_context=True)
async def eight_ball(context):
    possible_responses = [
        'That is a resounding no',
        'It is not looking likely',
        'Too hard to tell',
        'It is quite possible',
        'Definitely',
    ]
    await client.say(
        random.choice(possible_responses) + ", " +
        context.message.author.mention)

Exemplo n.º 28
0
#!/usr/bin/env python3
import random
import traceback
import pkgutil
import importlib
from discord.ext.commands import Bot, MissingRequiredArgument, BadArgument, NoPrivateMessage, CommandNotFound
from util.prefix import command_prefix
from util.checks import VerificationError
from storage import settings
from storage.db import DatabaseInterface

bot = Bot(command_prefix)

dburl = settings.load('Database').get('url')
bot.database = DatabaseInterface(dburl)
steamurl = settings.load('Database').get('url')
bot.steamdb = DatabaseInterface(steamurl)
# event code remains here for now
sass = [
    "I don't {} your {}.", "I can't {} a {}, you donut.",
    "No, you {} your {}.",
    "You should know that I can't {} a {} just like that..."
]
nope = ['No.', 'Nope.', 'Nah.', 'Your access level isn\'t high enough.']


@bot.event
async def on_ready():
    print('Ready (%s:%s)' % (bot.user.name, bot.user.id))

Exemplo n.º 29
0
1) Make it a music bot
2) Fix the dab issue cause your a horrible person
3) Write stuff for people LEL
4)Make Motd daily and wierd.
5) Introduce new users
6) Figure out the help command
7) Make it moonlight as Ryuk PLZ!
8) Change it to yuno at day
9) an offerring function????
10) Coffee to be served, i mean ya need to work ya bish!
"""

# Here you can modify the bot's prefix and description and wether it sends help in direct messages or not.
client = Bot(
    description=
    "Alright a little something i did for both expertimentaion and Hapiness. This is coffee",
    command_prefix="?",
    pm_help=False)


# This is what happens everytime the bot launches. In this case, it prints information like server count, user count the bot is connected to, and the bot id in the console.
# Do not mess with it because the bot can break, if you wish to do so, please consult me or someone trusted.
@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('Current Discord.py Version: {} | Current Python Version: {}'.format(
        discord.__version__, platform.python_version()))
Exemplo n.º 30
0
# Load In Saved Data
# Initialize Map Object
maps = {}
prev_message_was_stop = {}
prev_message_stop = {}
prev_message = {}
# Import the tasklist object or create new one
try:
    with open(task_path, 'rb') as file_input:
        tasklist = pickle.load(file_input)
except FileNotFoundError:
    tasklist = pokemap.Tasklist()

# Startup Bot Instance
client = Bot(command_prefix=bot_prefix)


# Sets the bots playing status
@client.event
async def on_ready():
    """Take actions on login."""
    await client.change_presence(game=Game(name=bot_game)
                                 )  # Sets the game presence
    print("Logged in as " + client.user.name)  # Logs sucessful login
    for server in client.servers:
        print(server.id)
        map_path = map_dir + str(server.id) + '.json'
        try:
            taskmap = pokemap.load(map_path)
            reset_bool = taskmap.reset_old()