repl.it
@Scoder12/

Shortlink Bot

Python

No description

fork
loading
Files
  • main.py
  • cogs
  • bot.log
  • database.py
  • requirements.txt
  • web_server.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import discord
from discord.ext import commands
import logging
import traceback
import os
import sys
import math
import web_server
import threading

logging.getLogger('discord').setLevel(logging.INFO)
logging.getLogger('werkzeug').setLevel(logging.ERROR)
logging.getLogger('web_server').setLevel(logging.DEBUG)
logger = logging.getLogger('sbot')
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
fh = logging.FileHandler('bot.log')
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)

logger.info("Loading... ")
flaskthread = threading.Thread(target=web_server.run)
flaskthread.start()

PREFIX = ","
bot = commands.Bot(command_prefix=PREFIX, description="Shortlink Bot")

@bot.event
async def on_ready():
    await bot.change_presence(activity=discord.Game(name="with APIs | ,help"))
    logger.info("Ready. ")
    logger.info("Logged in as " + str(bot.user) + "\n")
    servers = bot.guilds
    logger.info("Connected to " + str(len(servers)) + " server(s): ")
    #for i in servers:
    #    logger.info("\t" + str(i.name))
    logger.info("Listening...")

@bot.event
async def on_command_error(ctx, error):
    # if command has local error handler, return
    if hasattr(ctx.command, 'on_error'):
        return

    # get the original exception
    error = getattr(error, 'original', error)
    if isinstance(error, commands.CommandNotFound):
        return

    if isinstance(error, commands.BotMissingPermissions):
        missing = [perm.replace('_', ' ').replace('guild', 'server').title() for perm in error.missing_perms]
        if len(missing) > 2:
            fmt = '{}, and {}'.format("**, **".join(missing[:-1]), missing[-1])
        else:
            fmt = ' and '.join(missing)
        _message = 'I need the **{}** permission(s) to run this command.'.format(fmt)
        await ctx.send(_message)
        return

    if isinstance(error, commands.DisabledCommand):
        await ctx.send('This command has been disabled.')
        return

    if isinstance(error, commands.CommandOnCooldown):
        await ctx.send("This command is on cooldown, please retry in {}s.".format(math.ceil(error.retry_after)))
        return

    if isinstance(error, commands.MissingPermissions):
        missing = [perm.replace('_', ' ').replace('guild', 'server').title() for perm in error.missing_perms]
        if len(missing) > 2:
            fmt = '{}, and {}'.format("**, **".join(missing[:-1]), missing[-1])
        else:
            fmt = ' and '.join(missing)
        _message = 'You need the **{}** permission(s) to use this command.'.format(fmt)
        await ctx.send(_message)
        return
    
    if isinstance(error, commands.errors.MissingRequiredArgument):
        await ctx.send("A required argument is missing: %s" % error)
        return

    if isinstance(error, commands.UserInputError):
        await ctx.send("Invalid input.")
        #await self.send_command_help(ctx)
        return

    if isinstance(error, discord.errors.Forbidden):
        await ctx.send("Oops! I'm not allowed to do that. %s" % error)
        return

    if isinstance(error, commands.NoPrivateMessage):
        try:
            await ctx.author.send('This command cannot be used in direct messages.')
        except discord.Forbidden:
            pass
        return

    if isinstance(error, commands.CheckFailure):
        await ctx.send("You do not have permission to use this command.")
        return

    # ignore all other exception types, but print them to stderr
    print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)

    traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
    ch = bot.get_channel(521501219303456788)
    t = traceback.format_exception(type(error), error, error.__traceback__)
    await ch.send(ctx.message.content + "\n```" + "".join(t) + "```")


token = os.environ.get("BOT_TOKEN")
if token == None:
    print("Sorry, you must be repl owner to run this bot.  ")
    sys.exit(1)
initial_extensions = ['cogs.shorten', 'cogs.misc', 'cogs.admin', 'cogs.imgur']

if __name__ == '__main__':
    logger.info("Loading cogs...")
    for extension in initial_extensions:
        #print("Loading cog " + extension + "... ", end="")
        try:
            bot.load_extension(extension)
        except Exception:
            logger.critical('Failed to load extension %s.' % extension)
            traceback.print_exc()
        #print("Done. ")
    #print("All cogs loaded.  ")

    logger.info("Running bot... ")
    bot.run(token)
    logger.error(str(type(e)) + str(e))