예제 #1
0
 async def on_ready(self):
     print("on_ready fired")
     for k, v in Channel_ids.items():
         self.consts["ch"][k] = self.get_channel(v)
     g = self.get_guild(Official_discord_id)
     for oe in g.emojis:
         self.oemojis[oe.name] = oe
     g = self.get_guild(Sub_discord_id)
     for oe in g.emojis:
         self.oemojis[oe.name] = oe
     for i in range(11):
         self.consts["ne"].append(self.oemojis["b" + str(i)])
     if not emergency:
         await self.get_channel(934611880146780200).send("em:shutdown")
     bot.load_extension("jishaku")
     bot.load_extension("dpy_peper")
     bot.load_extension("discord.ext.components")
     if not self.debug:
         self.DBL_client = topgg.DBLClient(self, dbl_token, autopost=True)
     for o in os.listdir("./cogs"):
         if o.endswith(".py") and not o.startswith("_"):
             with open(f"./cogs/{o}") as f:
                 if f.read().startswith("# -*- ignore_on_debug -*-") and self.debug:
                     continue
             try:
                 bot.load_extension("cogs." + os.path.splitext(os.path.basename(o))[0])
             except Exception as e:
                 print("!! Failed to load extension: ", e)
                 traceback.print_exc()
     self.levenshtein = levenshtein.Levenshtein(self, max_length=1)
     print("on_ready done")
예제 #2
0
async def test_DBLClient_get_bot_votes_with_no_default_bot_id():
    client = topgg.DBLClient("TOKEN")
    with pytest.raises(
        errors.ClientException,
        match="you must set default_bot_id when constructing the client.",
    ):
        await client.get_bot_votes()
예제 #3
0
async def test_closed_DBLClient_raises_exception():
    client = topgg.DBLClient("TOKEN")
    assert not client.is_closed
    await client.close()
    assert client.is_closed
    with pytest.raises(errors.ClientException, match="client has been closed."):
        await client.get_weekend_status()
예제 #4
0
async def test_DBLClient_get_guild_count_with_no_id(
    method: t.Callable, kwargs: t.Dict[str, t.Any]
):
    client = topgg.DBLClient("TOKEN")
    with pytest.raises(
        errors.ClientException, match="bot_id or default_bot_id is unset."
    ):
        await method(client, **kwargs)
예제 #5
0
 def __init__(self, bot: "Bot"):
   self.bot = bot
   self.token = os.getenv("TOKENDBL")
   self.topgg = topgg.DBLClient(self.bot, self.token, autopost=False)
   if self.bot.cluster_idx == 0:
     if not hasattr(self.bot, "topgg_webhook"):
       self.bot.topgg_webhook = topgg.WebhookManager(self.bot).dbl_webhook("/dblwebhook", os.environ["DBLWEBHOOKPASS"])
       self.bot.topgg_webhook.run(5000)
     self.update_votes.start()
예제 #6
0
 def __init__(self, bot, prefix):
     self.bot = bot
     self.prefix = prefix
     self.token = os.getenv("DBL_TOKEN")  # set this to your DBL token
     self.topggpy = topgg.DBLClient(self.bot, self.token)
     self.post_server_cnt.start()
     self.update_station_stat.start()
     self.whos_playing.start()
     self.post_bot_stats.start()
예제 #7
0
파일: bot.py 프로젝트: Axelancerr/Life
    def __init__(self) -> None:
        super().__init__(
            status=discord.Status.dnd,
            activity=discord.Activity(type=discord.ActivityType.playing,
                                      name="aaaaa!"),
            allowed_mentions=discord.AllowedMentions(everyone=False,
                                                     users=True,
                                                     roles=True,
                                                     replied_user=False),
            help_command=custom.HelpCommand(),
            intents=discord.Intents.all(),
            command_prefix=self.get_prefix,
            case_insensitive=True,
            owner_ids=config.OWNER_IDS,
        )
        self._BotBase__cogs = commands.core._CaseInsensitiveDict()

        self.session: aiohttp.ClientSession = aiohttp.ClientSession()
        self.process: psutil.Process = psutil.Process()
        self.socket_stats: collections.Counter = collections.Counter()

        self.ERROR_LOG: discord.Webhook = discord.Webhook.from_url(
            session=self.session, url=config.ERROR_WEBHOOK_URL)
        self.GUILD_LOG: discord.Webhook = discord.Webhook.from_url(
            session=self.session, url=config.GUILD_WEBHOOK_URL)
        self.DMS_LOG: discord.Webhook = discord.Webhook.from_url(
            session=self.session, url=config.DM_WEBHOOK_URL)

        self.db: asyncpg.Pool = utils.MISSING
        self.redis: aioredis.Redis | None = None

        self.scheduler: aioscheduler.Manager = aioscheduler.Manager()
        self.mystbin: mystbin.Client = mystbin.Client(session=self.session)
        self.slate: obsidian.NodePool[Life, custom.Context,
                                      custom.Player] = obsidian.NodePool()
        self.ipc: ipc.Server = ipc.Server(bot=self,
                                          secret_key=config.SECRET_KEY,
                                          multicast_port=config.MULTICAST_PORT)

        self.topgg: topgg.DBLClient | None = topgg.DBLClient(
            bot=self, token=config.TOPGG, autopost=True
        ) if config.ENV is enums.Environment.PRODUCTION else None

        self.user_manager: managers.UserManager = managers.UserManager(
            bot=self)
        self.guild_manager: managers.GuildManager = managers.GuildManager(
            bot=self)

        self.first_ready: bool = True
        self.start_time: float = time.time()

        self.add_check(checks.global_check, call_once=True)  # type: ignore

        self.converters |= values.CONVERTERS
예제 #8
0
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
import hikari

import topgg

from .callbacks import autopost, webhook

app = hikari.GatewayBot("TOKEN")
webhook_manager = topgg.WebhookManager().set_data(app).endpoint(
    webhook.endpoint)
dblclient = topgg.DBLClient("TOPGG_TOKEN").set_data(app)
autoposter: topgg.AutoPoster = (dblclient.autopost().on_success(
    autopost.on_autopost_success).on_error(autopost.on_autopost_error).stats(
        autopost.stats))


@app.listen()
async def on_started(event: hikari.StartedEvent):
    me: hikari.OwnUser = event.app.get_me()
    assert me is not None
    dblclient.default_bot_id = me.id

    # since StartedEvent is a lifetime event
    # this event will only get dispatched once
    autoposter.start()
    await webhook_manager.start(6000)
예제 #9
0
import topgg

from data.config import Config
from data.secure_folder import Login
from data.useful import Ids

if Config["top_gg"]:
    Dbl_client = topgg.DBLClient(token=Login["top_gg"]["token"],
                                 default_bot_id=Ids["Bot"])
예제 #10
0
파일: main.py 프로젝트: SSagun-c/Hugo.py
    except:

        return commands.when_mentioned_or(client.DEFAULT_PREFIX)(client,
                                                                 message)


topggtoken = os.getenv("topgg")
token = os.getenv("DISCORD_TOKEN")
client = commands.Bot(command_prefix=get_prefix,
                      intents=Intents.all(),
                      case_insensitive=True)
client.DEFAULT_PREFIX = "h!"
client.remove_command('help')

dbl_token = topggtoken
client.topgg = topgg.DBLClient(client, dbl_token)

# Events


@tasks.loop(seconds=120)
async def change_status():

    status = cycle([f'{len(client.guilds)}'])

    await client.change_presence(activity=discord.Game(next(status)))


@client.event
async def on_ready():
예제 #11
0
async def test_DBLClient_post_guild_count_with_no_args():
    client = topgg.DBLClient("TOKEN", default_bot_id=1234)
    with pytest.raises(TypeError, match="stats or guild_count must be provided."):
        await client.post_guild_count()
예제 #12
0
def client() -> topgg.DBLClient:
    client = topgg.DBLClient(token="TOKEN", default_bot_id=1234)
    client.http = mock.Mock(topgg.http.HTTPClient)
    return client
예제 #13
0
slash = SlashCommand(bot, sync_commands=True)


menu = DefaultMenu("◀️", "▶️", "❌")  # You can copy-paste any icons you want.
ending_note = "Type {help.clean_prefix}help command to get information on a command\nType {help.clean_prefix}help category to get information on a category\nPlease do not put text in <> or []\n<> = mandatory argument, [] = optional argument"
bot.help_command = PrettyHelp(
    navigation=menu, color=discord.Colour.red(), ending_note=ending_note
)


bot.topgg_webhook = topgg.WebhookManager(bot).dbl_webhook("/dblwebhook", "dbl_password")
bot.topgg_webhook.run(4355)

dbl_token = os.environ["TOPGGTOKEN"]
bot.topggpy = topgg.DBLClient(bot, dbl_token, autopost=True, post_shard_count=True)


@bot.event
async def on_autopost_success():
    print(
        f"Posted server count ({bot.topggpy.guild_count}), shard count ({bot.shard_count})"
    )


@bot.event
async def on_dbl_vote(data):
    """An event that is called whenever someone votes for the bot on Top.gg."""
    if data["type"] == "test":
        # this is roughly equivalent to
        # return await on_dbl_test(data) in this case
예제 #14
0
 def __init__(self, bot):
     self.bot = bot
     self.topgg = topgg.DBLClient(bot, config('dbl_token'))
     if not self.bot.debug_token:
         self.bot.loop.create_task(self.update_stats())