Example #1
0
    def __init__(self, bot):

        self.bot = bot

        self.config = default.get("config.json")

        self._last_result = None
Example #2
0
    def __init__(self, bot):

        self.bot = bot

        self.config = default.get("config.json")

        self.process = psutil.Process(os.getpid())
Example #3
0
    async def on_message(self, msg):
        blacklist = default.get("blacklist.json")

        if (
            not self.is_ready()
            or msg.author.bot
            or not permissions.can_send(msg)
            or msg.guild is None
            or msg.author.id in blacklist
        ):
            return
        if (
            (
                msg.channel.id == 445658065933434892
                or msg.channel.id == 510141164179947574
                or msg.channel.id == 445659536016277514
            )
            and (msg.attachments or "http" in msg.content)
            and not msg.author.bot
        ):
            upvote = self.get_emoji(507362047059689472)
            await msg.add_reaction(upvote)
            await self.process_commands(msg)
        else:
            await self.process_commands(msg)
Example #4
0
async def check_permissions(ctx, perms, *, check=all):
    owners = default.get('config.json').owners
    if ctx.author.id in owners:
        return True

    resolved = ctx.channel.permissions_for(ctx.author)
    return check(
        getattr(resolved, name, None) == value
        for name, value in perms.items())
    async def on_ready(self):
        print(f'Ready: {self.bot.user} | Servers: {len(self.bot.guilds)}')
        stats.append_value("bots", self.bot.user.id)

        if not default.get("stats.json").started:
            stats.change_value(started=True)
            print(f"{self.bot.user} was first to boot, waiting for the other bot to boot")

            waiter = asyncio.ensure_future(default.wait_for(len(botstats.bots), 2))
            waiter.cancel()

            await self.bot.get_channel(config.channel).send(config.startMessage)
            print("Detected other bot, starting conversation...")

        while True:
            await asyncio.sleep(10)
            data = default.get("stats.json")
            if (time.time() - data.lastTalked) > 600 and self.bot.user.id == data.bots[0]:
                await self.bot.get_channel(config.channel).send(data.startMessage)
Example #6
0
 def __init__(self, bot):
     self.bot = bot
     self.config = default.get("./utils/cfg.json")
     self.benefits_register = {}
     self.slot_register = {}
     self.db = shelve.open("./data/db/economy/data.db", writeback=True)
     with open("./data/settings/economy.json") as s:
         self.settings = json.load(s)
         with open("./data/settings/deltimer.json") as f:
             self.deltimer = json.load(f)
    async def on_message(self, msg):
        if msg.author.id == self.bot.user.id:
            return

        if msg.channel.id == config.channel and msg.author.bot:
            async with msg.channel.typing():
                stats.change_value(lastTalked=int(round(time.time())))  # Record when there was last a response

                if default.get("stats.json").reset:
                    print(f"{self.bot.user} detected a reset and has completed it.")
                    stats.change_value(reset=False)
                    await asyncio.sleep(4)  # Let's keep the typing a bit more realistic huh?
                    return await msg.channel.send(default.get("stats.json").startMessage)

                response = await client.ask(msg.content)
                await msg.channel.send(response)

                if not default.get("stats.json").reset:
                    stats.change_value(
                        startMessage=response,
                        talked=default.get("stats.json").talked + 1
                    )
Example #8
0
 def __init__(self, bot):
     self.config = default.get("config.json")
     self.data = {}
     self.bot = bot
     self.trello_client = ''
     self.discord_tk = self.config.discord_token
     self.trello_ky = self.config.trello_key
     self.trello_tk = ''
     self.bot_color = 0xf0efc8
     self.channel = ''
     self.join_message = self.config.join_message
     self.current_game = self.config.playing
     self.last_reminded = datetime.datetime.now().date()
     self.current_working_board = ''
Example #9
0
 async def on_ready(self):
     """ Event to initialize bot tasks and other bot functions"""
     self.bot.loop.create_task(self.daily_reminder_task())
     if(self.trello_tk == ''):
         #read
         file = Path("data.json")
         if(file.is_file()):
              save = default.get("data.json")
              if(getattr(save, 'trello', False)):
                  print("Reading token value from file: " + save.trello[0].trello_tk)
                  self.trello_tk = save.trello[0].trello_tk
                  self.trello_client = TrelloClient(
                      api_key=self.trello_ky,
                      token=self.trello_tk
                  )
                  self.data['trello'] = []
                  self.data['trello'].append({
                      'trello_tk': self.trello_tk
                  })
 async def stats(self, ctx):
     """ Shows some basic stats """
     stats = default.get("stats.json")
     ram = self.process.memory_full_info().rss / 1024**2
     uptime = f_time(datetime.datetime.now() - self.bot.startup)
     embed = discord.Embed(color=0xbe2f2f,
                           title=f"**__Some Basic Stats__**")
     embed.add_field(name=u'📤 Messagses send in total',
                     value=stats.talked,
                     inline=False)
     embed.add_field(name=u'✏ Last message',
                     value=stats.startMessage,
                     inline=False)
     embed.add_field(name=u'💾 RAM Usage',
                     value=f'{ram:.2f} MB',
                     inline=False)
     embed.add_field(name=u'🕓 Uptime', value=uptime, inline=False)
     embed.add_field(name='⏱ Latency',
                     value=f'{round(self.bot.latency * 1000)} ms',
                     inline=False)
     await ctx.send(embed=embed)
Example #11
0
    async def whalelist(self, ctx, page: int = 1):
        """ View the whalelist (leaderboard) """
        owners = default.get("config.json").owners
        user = await author.get(ctx.author)
        per_page = self.config.game.whalelist_per_page
        page_count = 1
        _whales = User.find()
        whales = []
        # add the networth to each user and remove users excluded from whale lists
        for i, doc in enumerate(_whales):
            if int(doc['user_id']) not in owners:
                if doc['name'] != self.bot.user.name:
                    coin_list = await coins.get_coins(user['quote_to'])

                    doc_pvalue = await coins.portfolio_value(
                        doc, coin_list, user['quote_to'])
                    doc['game']['networth'] = float(
                        '{0:.2f}'.format(doc["game"]["money"] +
                                         doc["game"]["in_pocket"] +
                                         doc_pvalue))
                    whales.append(doc)
        whales = sorted(whales,
                        key=curried.get_in(['game', 'networth']),
                        reverse=True)
        if len(whales) > per_page:
            whales = default.divide_chunks(whales, per_page)[page - 1]
            page_count = len(whales)
        whale_list = ''
        if page > page_count:
            return
        for i, doc in enumerate(whales):
            rates = await coins.rate_convert(doc['quote_to'])
            doc = await coins.convert_user_currency(doc, rates,
                                                    user['quote_to'])

            whale_list += f'\n{i + 1}. {doc["name"]}{" " * (25 - len(doc["name"]))}{currency.symbol(user["quote_to"])}{doc["game"]["networth"]}'
        await ctx.send(
            f'```py\n{user["quote_to"]}\nBiggest whales:\n{whale_list}\n\nPage {page} of {page_count}```'
        )
Example #12
0
from utils import default

version = "v1.0.0"
invite = "https://discord.gg/bAE4QGy"
owners = default.get("config.json").owners


def is_owner(ctx):
    return ctx.author.id in owners
Example #13
0
	def __init__(self, bot):
		wikipedia.set_lang("pl")
		self.bot = bot
		self.config = default.get("config.json")
Example #14
0
 def __init__(self, client):
     self.client = client
     self.config = default.get("config.json")
     self.process = psutil.Process(os.getpid())
Example #15
0
def get(file):
    try:
        with open(file, encoding="utf8") as data:
            return json.load(data,
                             object_hook=lambda d: namedtuple("X", d.keys())
                             (*d.values()))
    except AttributeError:
        raise AttributeError("Unknown argument")
    except FileNotFoundError:
        raise FileNotFoundError("JSON file wasn't found")


version = "Stable v1.9.2"
invite = "https://discord.gg/V9DhKbW"
config = default.get("./utils/cfg.json")
economydb = shelve.open("./data/db/economy/data.db", writeback=True)
levelsdb = shelve.open("./data/db/levels/data.db", writeback=True)
warningsdb = shelve.open("./data/db/warnings/data.db", writeback=True)
JSON_VALIDATION = [
    'settings/deltimer.json', 'settings/logs.json', "settings/leveling.json"
]
ERRORS = ["deltimer", "logs", "leveling"]
dbcheck = os.path.exists(f"data/db/db.log")


class lib(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        with open("./data/settings/deltimer.json") as f:
            self.deltimer = json.load(f)
Example #16
0
 def __init__(self, bot):
     self.bot = bot
     self.counter = Counter()
     self.config = default.get("config.json")
     self.bot.loop.create_task(self.uptimer())
Example #17
0
 def __init__(self, bot):
     self.bot = bot
     self.config = default.get("config.json")
     self.session = aiohttp.ClientSession(loop=self.bot.loop)
import asyncio
import traceback
import time

from utils import default, cleverbot, stats
from discord.ext import commands
from discord.ext.commands import errors

config = default.get("config.json")
botstats = default.get("stats.json")
client = cleverbot.Caller(user=config.API.user, key=config.API.key, nick=config.API.nick)


async def send_cmd_help(ctx):
    if ctx.invoked_subcommand:
        _help = await ctx.bot.formatter.format_help_for(ctx, ctx.invoked_subcommand)
    else:
        _help = await ctx.bot.formatter.format_help_for(ctx, ctx.command)

    for page in _help:
        await ctx.send(page)


class Events(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_command_error(self, ctx, err):
        if isinstance(err, errors.MissingRequiredArgument) or isinstance(err, errors.BadArgument):
            await send_cmd_help(ctx)
Example #19
0
 def __init__(self, bot):
     self.bot = bot
     self.config = default.get("config.json")
     self.process = psutil.Process(os.getpid())
     channel = self.bot.get_channel(Channel id goes here)
Example #20
0
from pymongo import IndexModel
from pymongoext import DictField, StringField
from pymongoext.manipulators import Manipulator
from models import BaseModel
from utils import default

config = default.get("config.json")


class Guild(BaseModel):
    __schema__ = DictField(dict(
        name=StringField(required=True),
        guild_id=StringField(default=''),
    ))

    __indexes__ = [IndexModel('guild_id', unique=True)]

    # class InventoryAggregateManipulator(Manipulator):
    #     def transform_outgoing(self, doc, model):
    #
    #         return doc
    #
    #     def transform_incoming(self, doc, model, action):
    #
    #         return doc
Example #21
0
 def __init__(self, client):
     self.client = client
     self.config = default.get("config.json")
Example #22
0
 def __init__(self, bot):
     self.bot = bot
     self.config = default.get("config.json")
     self.process = psutil.Process(os.getpid())
     self.launch_time = datetime.utcnow()
     bot.remove_command('help')
Example #23
0
from utils import default

version = "v1.3.0"
invite = "https://discord.gg/s4bSSCG"
owners = default.get("config.json").owners
contributors = default.get("config.json").contributors
beta = default.get("config.json").beta


def is_owner(ctx):
    return ctx.author.id in owners


def is_beta(ctx):
    return ctx.author.id in beta


def is_contributor(ctx):
    return ctx.author.id in contributors


def has_userid(ctx, userid):
    return ctx.author.id in userid


def has_guildid(ctx, guildid):
    return ctx.guild.id in guildid


def has_channelid(ctx, channelid):
    return ctx.channel.id in channelid
Example #24
0
 def bot_check_once(self, ctx):
     blacklist = default.get("config.json").blacklist
     if ctx.author.id in blacklist:
         raise Blacklisted()
     else:
         return True
Example #25
0
 def __init__(self, bot):
     self.bot = bot
     self.config = default.get("config.json")
     self.osu_key = self.config.osu_api_key
Example #26
0
from utils import default

version = default.get("config.json").version
owners = default.get("config.json").owners


def is_owner(ctx):
    return ctx.author.id in owners
Example #27
0
 def __init__(self, bot):
     self.bot = bot
     self.config = default.get("config.json")
Example #28
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from utils.data import Bot, HelpFormat
from utils.default import get

cfg = get("config.json")

bot = Bot(command_prefix=cfg.prefix,
          prefix=cfg.prefix,
          command_attrs=dict(hidden=True),
          help_command=HelpFormat(),
          case_insensitive=True)

bot.run(cfg.token)
Example #29
0
 def __init__(self, bot):
     self.bot = bot
     self.config = default.get("./utils/cfg.json")
     with open("./data/settings/deltimer.json") as f:
         with open("./data/settings/deltimer.json") as f:
             self.deltimer = json.load(f)
Example #30
0
File: main.py Project: greek/toilet
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

import os
import random

from utils import default
from utils.data import Bot, HelpFormat

quotes = [
    "reee", "ready to flush owo", "poop", "poop funny!", "OwO what's this?",
    "h", "um :flushed:", "The token is 5."
]

config = default.get("src/config.json")
print("---", random.choice(quotes), "---")

bot = Bot(command_prefix=config.prefix,
          prefix=config.prefix,
          command_attrs=dict(hidden=True),
          help_command=HelpFormat())

for file in os.listdir("src/cogs"):
    if file.endswith(".py"):
        name = file[:-3]
        bot.load_extension(f"cogs.{name}")

bot.run(config.token)