Esempio n. 1
0
File: bot.py Progetto: Ryuk264/Life
    def __init__(self, loop) -> None:
        super().__init__(command_prefix=self.get_prefix,
                         reconnect=True,
                         help_command=help.HelpCommand(),
                         loop=loop,
                         activity=discord.Streaming(
                             name=f'{config.Config(bot=self).prefix}help',
                             url='https://www.twitch.tv/axelancerr'),
                         intents=discord.Intents(guilds=True,
                                                 members=True,
                                                 bans=False,
                                                 emojis=False,
                                                 integrations=False,
                                                 webhooks=False,
                                                 invites=False,
                                                 voice_states=True,
                                                 presences=True,
                                                 messages=True,
                                                 reactions=True,
                                                 typing=False))

        self.text_permissions = discord.Permissions(read_messages=True,
                                                    send_messages=True,
                                                    embed_links=True,
                                                    attach_files=True,
                                                    read_message_history=True,
                                                    add_reactions=True,
                                                    external_emojis=True)
        self.voice_permissions = discord.Permissions(connect=True,
                                                     speak=True,
                                                     use_voice_activation=True)

        self.session = aiohttp.ClientSession(loop=self.loop)
        self.log = logging.getLogger(name='bot')
        self.config = config.Config(bot=self)
        self.utils = utils.Utils(bot=self)

        self.guild_manager = guild_manager.GuildConfigManager(bot=self)
        self.user_manager = user_manager.UserConfigManager(bot=self)

        self.socket_stats = collections.Counter()
        self.process = psutil.Process()
        self.start_time = time.time()

        self.mentions_dms_webhook = discord.Webhook.from_url(
            url=self.config.mentions_dms_url,
            adapter=discord.AsyncWebhookAdapter(self.session))
        self.logging_webhook = discord.Webhook.from_url(
            url=self.config.logging_url,
            adapter=discord.AsyncWebhookAdapter(self.session))
        self.errors_webhook = discord.Webhook.from_url(
            url=self.config.errors_url,
            adapter=discord.AsyncWebhookAdapter(self.session))

        self.invite = f'https://discord.com/oauth2/authorize?client_id=628284183579721747&scope=bot&permissions=37080128'
        self.github = f'https://github.com/Axelancerr/Life'
        self.dashboard = f'https://dashboard.mrrandom.xyz/'
        self.support = f'https://discord.gg/xP8xsHr'

        self.commands_not_allowed_dms = {
            'join', 'play', 'leave', 'skip', 'pause', 'unpause', 'seek',
            'volume', 'now_playing', 'queue', 'queue detailed', 'queue loop',
            'queue sort', 'queue shuffle', 'queue remove', 'queue history',
            'queue history detailed', 'queue history clear', 'queue clear',
            'queue reverse', 'queue move', 'lavalink', 'icon', 'banner',
            'splash', 'server', 'channels', 'member', 'tag', 'tag alias',
            'tag list', 'tag edit', 'tag create', 'tag transfer', 'tag all',
            'prefix search', 'tag delete', 'tag info', 'tag claim', 'tag raw',
            'settings prefix add', 'settings prefix remove',
            'settings prefix clear', 'settings colour set',
            'settings colour clear'
        }

        self.first_ready = True

        self.wolframalpha = None
        self.http_client = None
        self.http_server = None
        self.lavalink = None
        self.imaging = None
        self.ksoft = None
        self.redis = None
        self.db = None
Esempio n. 2
0
print('Please wait...')
from discord.ext import commands
from datetime import datetime
from os import environ
from modules import *
from time import time
import discord
import framework

framework.modify_discord_py_functions()
prefix = framework.get_prefix()

client = commands.Bot(command_prefix=prefix,
                      intents=discord.Intents(guilds=True,
                                              members=True,
                                              emojis=True,
                                              guild_reactions=True,
                                              guild_messages=True),
                      activity=discord.Activity(type=5, name=f"{prefix}help"),
                      max_messages=100)

framework.initiate(client)
pre_ready_initiation(client)

client.util.mobile_indicator()


@client.event
async def on_ready():
    await post_ready_initiation(client)
    client.util.load_cogs()
Esempio n. 3
0
from keep_alive import keep_alive
import os
import discord
from discord.ext import commands,tasks
import requests, json, io, contextlib


#------------------CONFIGS------------------
token = os.environ['TOKEN']
prefix = os.environ['prefix']

intents = discord.Intents().all()
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix=["t,", "T,", "<@!824888045622394910> ", "<@824888045622394910> ", "teny ", "Teny ", "Tény ", "tény "], help_command=None,intents=intents)

owner = [740845704326676493, 575263293015588867]
#------------------CONFIGS------------------
def err(msg):
  er = discord.Embed(title="", description='', color=0xe74c3c)
  er.set_author(name=msg,icon_url="https://cdn.discordapp.com/attachments/804212727869866006/824902921505865749/772509.png")
  return er


#------------------COMMANDS------------------

@bot.event
async def on_ready():
  print("100% loaded!")

@bot.command()
async def ping(ctx):
Esempio n. 4
0
File: bot.py Progetto: elfq/HyLink
            )

        except asyncio.TimeoutError:
            await ctx.author.send("**Timeout:** You didn't react in time.")

        else:
            if str(reaction.emoji) == "✅":
                embed = discord.Embed(color=discord.Colour.purple())
                embed.set_author(
                    name="Please enter your Minecraft username.",
                    icon_url=self.bot.user.avatar_url,
                )
                await ctx.author.send(embed=embed)
                ign = await self.bot.wait_for("message")
                r = requests.get(
                    f"https://api.hypixel.net/player?key={environ.get('API_KEY')}&name={ign.content}"
                )
                if r.json()["player"]["socialMedia"]["links"]["DISCORD"] == ctx.author:
                    await ctx.author.send("✅ You've been verified!")
                    await ctx.author.edit(nick=ign.content)
                    await ctx.author.add_roles("Verified")
                else:
                    await ctx.author.send(
                        ":x: Couldn't verify you, this could be due to you not having your discord linked, or your IGN is incorrect."
                    )


bot = commands.Bot(command_prefix="!", intents=intents=discord.Intents(guilds=True, messages=True, reactions=True))
bot.add_cog(HyLink(bot))
bot.run(environ.get("TOKEN"))
Esempio n. 5
0
import os, sys, discord, platform, random, aiohttp, json
from discord.ext import commands

intents = discord.Intents(members=True)


class Example2(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None

    @commands.command()
    async def yodawg(self, ctx, *, member: discord.Member = None):
        await ctx.send('here dawg.')
        member = member or ctx.author
        if self._last_member is None or self._last_member.id != member.id:
            await ctx.send('sup {0.mention} dawg~'.format(member))


def setup(bot):

    bot.add_cog(Example2(bot))
Esempio n. 6
0
File: chie.py Progetto: Xeuz-x/Chie
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

import discord
from datetime import datetime
from discord.ext import commands
from core.reactor import startup
from chieUtils import config
from chieUtils import event_logger as logger

if config.sharding == True:
    client = commands.AutoShardedBot(config.get_prefix, shard_count = config.shards, intents = discord.Intents().all())
    logger.INFO(__name__, f"Generated {config.shards} shards")

elif config.sharding == False:
    client = commands.Bot(config.get_prefix, intents = discord.Intents().all())

@client.event
async def on_ready():
    print(f"Live {datetime.now().strftime('%m-%d-%Y')}")
    await client.change_presence(activity = discord.Activity(type = discord.ActivityType.watching, name = 'over you.'))
    logger.INFO(__name__, '{0.user} is online.'.format(client))

startup(client, config.get_token)
Esempio n. 7
0
        self.ldclient.close()


desc = '''
Avrae, a D&D 5e utility bot designed to help you and your friends play D&D online.
A full command list can be found [here](https://avrae.io/commands)!
Invite Avrae to your server [here](https://invite.avrae.io)!
Join the official development server [here](https://support.avrae.io)!
'''
intents = discord.Intents(
    guilds=True,
    members=True,
    messages=True,
    reactions=True,
    bans=False,
    emojis=False,
    integrations=False,
    webhooks=False,
    invites=False,
    voice_states=False,
    presences=False,
    typing=False
)  # https://discord.com/developers/docs/topics/gateway#gateway-intents
bot = Avrae(
    prefix=get_prefix,
    description=desc,
    pm_help=True,
    testing=config.TESTING,
    activity=discord.Game(name=f'D&D 5e | {config.DEFAULT_PREFIX}help'),
    allowed_mentions=discord.AllowedMentions.none(),
    intents=intents,
    chunk_guilds_at_startup=False)
Esempio n. 8
0
from discord.ext.commands import Paginator
import utility.initdb as i
import discord
from tortoise import run_async
from help_command import PaginatedHelpCommand
import os
import json

extlist = [
    "jishaku", "utility", "moderation", "images", "economy", "owner", "fun",
    "voice"
]
botprefix = ""
token = ""
intents = discord.Intents(messages=True,
                          guilds=True,
                          members=True,
                          presences=True)

try:
    with open("config.json") as opts:
        opts = json.loads(opts.read())
        botprefix = opts["prefix"] or "d::"
        token = opts["token"]
except Exception as e:
    print(
        "Something went wrong. Make sure your config.json is valid and all keys are filled in."
    )
    print(e)
    exit()

with open("classes/botowners.txt", "r") as botowners:
Esempio n. 9
0
import os

import discord
from discord.ext import commands

import config

bot = commands.Bot(command_prefix=commands.when_mentioned_or("%"),
                   owner_ids=config.OWNER_IDS,
                   intents=discord.Intents(guilds=True,
                                           members=True,
                                           voice_states=True,
                                           messages=True,
                                           reactions=True,
                                           emojis=True))

# bot variables
bot.OK_EMOJI = "sadcatthumbsup:758224306362253323"
bot.TZ = config.TIMEZONE

initial_extensions = (
    'jishaku',
    'cogs.classcord',
)

for exntension in initial_extensions:
    bot.load_extension(exntension)


@bot.event
async def on_ready():
Esempio n. 10
0
    def __init__(
            self,
            config_file: str = 'config/config.toml',
            logger: logging.Logger = None,
            activity: discord.Activity = discord.Game(name="Reconnecting..."),
            status: discord.Status = discord.Status.dnd,
            case_insensitive: bool = True,
            intents: discord.Intents = None,
            allowed_mentions: discord.AllowedMentions = discord.
        AllowedMentions(everyone=False),
            *args,
            **kwargs):
        """
        Args:
            config_file (str, optional): The path to the config file for the bot.
            logger (logging.Logger, optional): The logger object that the bot should use.
            activity (discord.Activity, optional): The default activity of the bot.
            status (discord.Status, optional): The default status of the bot.
            case_insensitive (bool, optional): Whether or not commands are case insensitive.
            intents (discord.Intents, optional): The default intents for the bot.
            allowed_mentions (discord.AllowedMentions, optional): The default allowed mentions for the bot.
            *args: The default args that are sent to the `discord.ext.commands.Bot` object.
            **kwargs: The default args that are sent to the `discord.ext.commands.Bot` object.
        """

        # Store the config file for later
        self.config = None
        self.config_file = config_file
        self.logger = logger or logging.getLogger('bot')
        self.reload_config()

        # Let's work out our intents
        if self.config.get('intents', {}):
            intents = discord.Intents(**self.config.get('intents', {}))
        else:
            intents = discord.Intents(guilds=True,
                                      guild_messages=True,
                                      dm_messages=True)

        # Run original
        super().__init__(
            command_prefix=get_prefix,
            activity=activity,
            status=status,
            case_insensitive=case_insensitive,
            intents=intents,
            allowed_mentions=allowed_mentions,
            *args,
            **kwargs,
        )

        # Set up our default guild settings
        self.DEFAULT_GUILD_SETTINGS = {
            'prefix': self.config['default_prefix'],
        }
        self.DEFAULT_USER_SETTINGS = {}

        # Aiohttp session
        self.session = aiohttp.ClientSession(loop=self.loop)

        # Allow database connections like this
        self.database = DatabaseConnection
        self.database.logger = self.logger.getChild('database')

        # Allow redis connections like this
        self.redis = RedisConnection
        self.redis.logger = self.logger.getChild('redis')

        # Allow Statsd connections like this
        self.stats = StatsdConnection
        self.stats.config = self.config.get('statsd', {})
        self.stats.logger = self.logger.getChild('statsd')

        # Store the startup method so I can see if it completed successfully
        self.startup_time = dt.now()
        self.startup_method = None

        # Regardless of whether we start statsd or not, I want to add the log handler
        handler = AnalyticsLogHandler(self)
        handler.setLevel(logging.DEBUG)
        logging.getLogger('discord.http').addHandler(handler)

        # Here's the storage for cached stuff
        self.guild_settings = collections.defaultdict(
            lambda: copy.deepcopy(self.DEFAULT_GUILD_SETTINGS))
        self.user_settings = collections.defaultdict(
            lambda: copy.deepcopy(self.DEFAULT_USER_SETTINGS))
Esempio n. 11
0
    logging.basicConfig(format=LOG_FMT, filename="bot.log")
logging.getLogger("discord").setLevel(LOG_LEVEL_API)
l.setLevel(LOG_LEVEL_BOT)

try:
    with open("admin.txt") as f:
        owner_id = int(f.read())
except IOError:
    owner_id = None

COMMAND_PREFIX = "!"

intents = discord.Intents(
    guilds=True,
    members=True,
    messages=True,
    message_content=True,
    reactions=True,
    emojis=True,
)

bot = commands.Bot(command_prefix=commands.when_mentioned_or(COMMAND_PREFIX),
                   case_insensitive=True,
                   status=discord.Status.dnd,
                   allowed_mentions=discord.AllowedMentions(everyone=False),
                   intents=intents)
bot.load_extension("jishaku")
bot.owner_id = owner_id
bot.needed_extensions = set(get_extensions())
bot.loaded_extensions = set()

Esempio n. 12
0
> Replace <client_id> with Client ID found in 'General Information' in your Application's page.

"""

LOGGING_FORMAT: str = '[%(asctime)-15s] [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s'
SHOOB_ID: int = 673362753489993749
TIMEOUT: int = 20
WAIT_DIFF: int = 2
BOT_TOKEN: str = "BOT TOKEN GOES HERE"

log: logging.Logger = logging.getLogger('discord')
logging.basicConfig(level=20,
                    format=LOGGING_FORMAT,
                    datefmt='%m/%d | %I:%M:%S')

intents: discord.Intents = discord.Intents().none()
intents.messages: bool = True
intents.guilds: bool = True

bot: discord.Client = discord.Client(intents=intents)


def is_spawn(message: discord.Message) -> Union[bool, None]:
    if message.embeds:
        embed: discord.Embed = message.embeds[0]
        return (embed.title and 'Tier' in embed.title and embed.image)


def is_claim(message: discord.Message) -> Union[bool, None]:
    if message.embeds:
        embed: discord.Embed = message.embeds[0]
Esempio n. 13
0
                async with cs.post("https://hastebin.com/documents",
                                   data=payload) as r:
                    post = await r.json()
                    uri = post["key"]
                    return f"https://hastebin.com/{uri}"
        except aiohttp.ClientResponseError:
            return discord.File(io.StringIO(content), filename="Traceback.txt")


intents = discord.Intents(
    guilds=True,
    members=True,
    bans=True,
    emojis=True,
    integrations=True,
    webhooks=True,
    invites=True,
    voice_states=True,
    presences=False,
    messages=True,
    reactions=True,
    typing=True,
)
miya = Miya(
    shard_count=3,
    command_prefix="미야야",
    strip_after_prefix=True,
    description="다재다능한 Discord 봇, 미야.",
    help_command=None,
    chunk_guilds_at_startup=True,
    intents=intents,
)
Esempio n. 14
0
    @menus.button("🔽")
    async def resend_message(self, payload):
        await self.message.delete()
        self.message = None
        await self.start(self.ctx)

    @menus.button("\N{BLACK SQUARE FOR STOP}\ufe0f")
    async def cancel(self, payload):
        user = discord.utils.get(self.players, id=payload.user_id)
        e = self.message.embeds[0]
        e.title = f"Game cancelled by {user.display_name}. Go boo them!"
        await self.message.edit(embed=e)
        self.end()


bot = commands.Bot(command_prefix="tii!", intents=discord.Intents(guilds=True, messages=True, members=True, reactions=True), help_command=None)
bot.load_extension("jishaku")
player_games = {}

@commands.max_concurrency(1, commands.BucketType.channel)
@commands.guild_only()
@bot.command(aliases=["d&b"])
async def dab(ctx, width: Optional[int] = 4, height: Optional[int] = 4, *others: discord.Member):
    if ctx.author in player_games:
        return await ctx.send("Hey, you're already playing a game!")
    if already := [other.display_name for other in others if other in player_games]:
        if len(already) == 1:
            group = already[0] + " is"
        elif len(already) == 2:
            group = f"{already[0]} and {already[1]} are"
        else:
Esempio n. 15
0
        print(f'Checking for git branch failed: {type(e).__name__} {e}')
        branch = '<unknown>'
    except FileNotFoundError as e:
        print('git not found, not showing branch')
        branch = '<unknown>'

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

config = configparser.ConfigParser()
config.read(join(data_dir, 'config.ini'))

post_startup_message = config['Main'].getboolean('post_startup_message',
                                                 fallback=True)

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

client = discord.Client(activity=discord.Game(name=config['Main']['playing']),
                        max_messages=100,
                        intents=intents)
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)
Esempio n. 16
0
def start(token, guild_id, interval=300):
    bot = HauntedGuild(guild_id, interval=interval, intents=discord.Intents().all())
    bot.run(token)
Esempio n. 17
0
#!/usr/bin/python3.9
import discord
from src.MyClient import MyClient
import os
from dotenv import load_dotenv

default_intents = discord.Intents()
default_intents = discord.Intents.default()
default_intents.members = True
client = MyClient(default_intents)
load_dotenv()
client.run(os.getenv("TOKEN"))
Esempio n. 18
0
File: bot.py Progetto: xezzz/AutoMod
class ShardedBotInstance(commands.AutoShardedBot):
    __slots__ = [
        "config"
        "ready", "locked", "avatar_as_bytes", "uptime", "last_reload",
        "used_commands", "used_tags", "command_stats", "ignore_for_events",
        "case_cmd_cache", "webhook_cache", "fetched_user_cache", "db", "cache",
        "emotes", "locale"
    ]

    intents = discord.Intents(guilds=True,
                              members=True,
                              bans=True,
                              emojis=True,
                              messages=True,
                              reactions=True,
                              typing=False,
                              voice_states=True)
    if hasattr(intents, "message_content"):
        intents.message_content = True

    def __init__(self, *args, **kwargs) -> None:
        with open("backend/config.json", "r", encoding="utf8",
                  errors="ignore") as config_file:
            self.config = Object(json.load(config_file))
        super().__init__(command_prefix=prefix_callable,
                         intents=self.intents,
                         case_insensitive=True,
                         max_messages=1000,
                         chunk_guilds_at_startup=False,
                         allowed_mentions=discord.AllowedMentions(
                             everyone=False, replied_user=False),
                         *args,
                         **kwargs)
        for f in [pages, embed]:
            f.inject_bot_obj(self)

        self.ready = False
        self.locked = False
        self.avatar_as_bytes = None
        self.error_log = None
        self.uptime = datetime.datetime.utcnow()
        self.last_reload = datetime.datetime.utcnow().timestamp()

        self.used_commands = 0
        self.used_tags = 0

        self.command_stats = {}
        self.ignore_for_events = []
        self.case_cmd_cache = {}
        self.webhook_cache = {}
        self.fetched_user_cache = {}

        if self.config.watch == True:
            self.observer = Observer(self)
        self.db = MongoDB(self)
        self.cache = InternalCache(self)
        self.emotes = Emotes(self)
        self.locale = Translator(self)

        self.run()

    async def on_ready(self) -> None:
        if self.config.custom_status != "":
            if self.activity == None:
                await self.change_presence(activity=discord.Activity(
                    type=discord.ActivityType.playing,
                    name=self.config.custom_status))

        if not self.ready:
            await self.load_plugins()
            if self.config.watch == True:
                await self.observer.start()
            for g in self.guilds:
                if not self.db.configs.exists(g.id):
                    self.db.configs.insert(
                        GuildConfig(g, self.config.default_prefix))

            m = self.guilds[0].me
            if m != None:
                if m.avatar != None:
                    self.avatar_as_bytes = await m.avatar.read()
                else:
                    self.avatar_as_bytes = None
            self.ready = True

    async def on_message(self, msg: discord.Message) -> None:
        if msg.author.bot or msg.guild is None:
            return
        ctx = await self.get_context(msg)
        if ctx.valid and ctx.command is not None:
            self.used_commands += 1
            disabled = self.db.configs.get(msg.guild.id, "disabled_commands")
            if ctx.command.name.lower() in disabled:
                if ctx.author.guild_permissions.manage_messages == False:
                    try:
                        await msg.add_reaction(self.emotes.get("LOCK"))
                    except Exception:
                        pass
                    finally:
                        return

            if self.ready:
                if not msg.guild.chunked:
                    await msg.guild.chunk(cache=True)

            await self.invoke(ctx)

    async def load_plugins(self) -> None:
        try:
            self.remove_command("help")
        except Exception:
            pass
        finally:
            for p in self.config.plugins:
                await self.load_plugin(p)
            self.plugins = self.cogs

    async def register_plugin(self, plugin: commands.Cog) -> None:
        await super().add_cog(plugin)

    async def load_plugin(self, plugin: str) -> None:
        try:
            await super().load_extension(f"backend.plugins.{plugin}")
        except Exception:
            log.error(f"❌ Failed to load {plugin} - {traceback.format_exc()}")
        else:
            log.info(f"🔥 Successfully loaded {plugin}")

    async def reload_plugin(self, plugin: str) -> None:
        if plugin == "mod":
            in_plugins_name = "ModerationPlugin"
        elif plugin == "rr":
            in_plugins_name = "ReactionRolesPlugin"
        else:
            in_plugins_name = f"{plugin.capitalize()}Plugin"
        if in_plugins_name not in self.plugins:
            try:
                await super().load_extension(f"backend.plugins.{plugin}")
            except Exception:
                raise

        else:
            try:
                await super().unload_extension(f"backend.plugins.{plugin}")
            except Exception:
                raise

            else:
                try:
                    await super().load_extension(f"backend.plugins.{plugin}")
                except Exception:
                    raise

    def get_plugin(self, name: str) -> Union[commands.Cog, None]:
        return super().get_cog(name)

    def handle_timeout(self, mute: bool, guild: discord.Guild,
                       user: Union[discord.Member,
                                   discord.User], iso8601_ts) -> str:
        exc = ""
        try:
            resp = requests.patch(
                f"https://discord.com/api/v9/guilds/{guild.id}/members/{user.id}",
                json={
                    "communication_disabled_until":
                    None if mute == False else iso8601_ts
                },
                headers={"Authorization": f"Bot {self.config.token}"})
            if resp.status_code != 200: exc = resp.text
        except Exception as ex:
            log.warn(
                f"⚠️ Error while trying to mute user ({user.id}) (guild: {guild.id}) - {ex}"
            )
            exc = ex
        finally:
            return exc

    def get_uptime(self, split: bool = False) -> str:
        raw = datetime.datetime.utcnow() - self.uptime

        hours, remainder = divmod(int(raw.total_seconds()), 3600)
        days, hours = divmod(hours, 24)
        minutes, seconds = divmod(remainder, 60)

        if split == False:
            return "{}d, {}h, {}m & {}s".format(days, hours, minutes, seconds)
        else:
            return days, hours, minutes, seconds

    def run(self) -> None:
        try:
            super().run(self.config.token, reconnect=True)
        finally:
            pass
Esempio n. 19
0
    exit(1)
if args.shardcount is not None and not (args.min is not None
                                        and args.max is not None):
    logger.critical("You set a shardcount but not min/max shards")
    exit(1)

# Set up intents
intents = discord.Intents(
    guilds=True,  # guild/channel join/remove/update
    members=True,  # member join/remove/update
    bans=False,  # member ban/unban
    emojis=False,  # emoji update
    integrations=False,  # integrations update
    webhooks=False,  # webhook update
    invites=False,  # invite create/delete
    voice_states=True,  # voice state update
    presences=False,  # member/user update for games/activities
    guild_messages=True,  # message create/update/delete
    dm_messages=True,  # message create/update/delete
    guild_reactions=True,  # reaction add/remove/clear
    dm_reactions=True,  # reaction add/remove/clear
    guild_typing=False,  # on typing
    dm_typing=False,  # on typing
)

# Okay cool make the bot object
bot = utils.Bot(
    config_file=args.config_file,
    activity=discord.Game(name="Reconnecting..."),
    status=discord.Status.dnd,
    case_insensitive=True,
Esempio n. 20
0
import configparser
from os import mkdir

import asyncpg
import discord
from cryptography.fernet import Fernet
from discord.ext import commands

bot = commands.Bot(command_prefix="-", intents=discord.Intents(guilds=True, members=True, messages=True))
config = configparser.ConfigParser()

psql_name = input("What is the username to sign into your PostgreSQL DB: ")
psql_pass = input("What is the password to sign into your PostgreSQL DB: ")
psql_db = input("Which database do you want to connect to (blank = default): ")
psql_ip = input("What is the IP for the PostgreSQL DB (blank = 127.0.0.1): ")
if psql_ip == "":
    psql_ip = "127.0.0.1"

token = input("Input a bot token: ")
main_server = int(input("What is the ID of the main server for your bot? (Suggestions, errors and DMs will be sent here): "))
trusted_ids = input("Input a list of trusted user IDs (allowing for moderation commands such as -(un)block, -dm, -refreshroles, -lookupinfo, and others.): ").split(", ")

mkdir("cache")

cache_key = Fernet.generate_key()
config["Main"] = {
    "token": token,
    "key": cache_key,
    "main_server": main_server,
    "trusted_ids": trusted_ids,
}
Esempio n. 21
0
import discord
import asyncio
from discord.ext import commands

from itertools import chain
import sys
import os
from platform import python_version

import logging
import traceback

# logging.basicConfig(level=logging.DEBUG)
# log = logging.getLogger(__name__)

intents = discord.Intents(messages=True, members=True, guild_messages=True)
description = """random utilities and shitposting bot"""
bot = commands.Bot(command_prefix="$",
                   case_insensitive=True,
                   description=description)


@bot.event
async def on_ready():
    print("Logged in as")
    print(bot.user.name)
    print(bot.user.id)
    print(f"Running python version {python_version()}")
    print("------")
    await bot.change_presence(activity=discord.CustomActivity(name="coping"))
Esempio n. 22
0
import discord, asyncio, os, platform, sys
from discord.ext.commands import Bot
from discord.ext import commands

if not os.path.isfile("config.py"):
    sys.exit("'config.py' not found! Please add it and try again.")
else:
    import config
"""	
Setup bot intents (events restrictions)
For more information about intents, please go to the following websites:
https://discordpy.readthedocs.io/en/latest/intents.html
https://discordpy.readthedocs.io/en/latest/intents.html#privileged-intents
"""
intents = discord.Intents().default()
intents.messages = True
intents.reactions = True
intents.presences = True
intents.members = True
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
Esempio n. 23
0
logger = logging.getLogger()
logger.setLevel(logging.INFO)
handler = logging.FileHandler(filename=f"discord-{cluster_id}.log", encoding="utf-8", mode="w")
handler.setFormatter(logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s"))
logger.addHandler(handler)

log = logging.getLogger(__name__)


def _get_guild_prefix(bot2, message):
    prefix = get_guild_prefix(bot2, message.guild)
    return commands.when_mentioned_or(prefix)(bot2, message)


bot = ModMail(
    intents=discord.Intents(guilds=True, members=True, presences=True, messages=True, reactions=True),
    member_cache_flags=None,
    chunk_guilds_at_startup=config.fetch_all_members,
    command_prefix=_get_guild_prefix,
    case_insensitive=True,
    help_command=None,
    owner_id=config.owner,
    heartbeat_timeout=300,
    shard_ids=shard_ids,
    shard_count=shard_count,
    cluster_id=cluster_id,
    cluster_count=cluster_count,
    version="2.1.0",
)

Esempio n. 24
0
import discord
from discord.ext import commands
import random
from random import choice
from random import randint
import os
import json

intents = discord.Intents()
intents.members = True
bot = commands.Bot(command_prefix = 'r!')
bot.remove_command('help')


@bot.event
async def on_ready():
    activity = discord.Game(name="r!help")
    await bot.change_presence(activity=discord.Game(name="r!help"))


@bot.command()
async def kill(ctx, member: discord.Member):
    await ctx.message.delete()
    await ctx.send('{} 🔫  {}.'.format(member.mention, ctx.message.author.mention))

@bot.command()
async def dickpic(ctx):
    await ctx.send('```\n...............00000000\n...............00000000000\n..............00,,,,,,,0,,,,,,00\n.............0,,,,,,,,,0,,,,,,,,,0\n............0,,,,,,,,,,0,,,,,,,,,,0\n...........0,,,,,,,,,,,0,,,,,,,,,,,0\n...........0,,,,,,,,,,,,,,,,,,,,,,,,0\n...........0,,,,,,,,,,,,,,,,,,,,,,,,0\n...........0,,,,,,,,,,,,,,,,,,,,,,,,0\n............0,,,,,,,,,,,,,,,,,,,,,0\n.............000000000000000\n.............0,,,,,,,,,,,,,,,,,,,0\n.............0,,,,,,,,,,,,,,,,,,,0\n.............0,,,,,,,,,,,,,,,,,,,0\n.............0,,,,,,,,,,,,,,,,,,,0\n.............0,,,,,,,,,,,,,,,,,,,0\n.............0,,,,,,,,,,,,,,,,,,,0\n.............0,,,,,,,,,,,,,,,,,,,0\n.............0,,,,,,,,,,,,,,,,,,,0\n.............0,,,,,,,,,,,,,,,,,,,0\n.............0,,,,,,,,,,,,,,,,,,,0\n.............0,,,,,,,,,,,,,,,,,,,0\n.............0,,,,,,,,,,,,,,,,,,,0\n.............0,,,,,,,,,,,,,,,,,,,0\n.............0,,,,,,,,,,,,,,,,,,,0\n.............0,,,,,,,,,,,,,,,,,,,0\n.............0,,,,,,,,,,,,,,,,,,,0\n.........000,,,,,,,,,,,,,,,,,,,,,,000\n.......00,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,00\n......0,,,,,,,,,,,,,,,,,0,,,,,,,,,,,,,,,,0\n.....0,,,,,,,,,,,,,,,,,,,0,,,,,,,,,,,,,,,,0\n....0,,,,,,,,,,,,,,,,,,,,,0,,,,,,,,,,,,,,,,0\n...0,,,,,,,,,,,,,,,,,,,,,,0,,,,,,,,,,,,,,,,0\n...0,,,,,,,,,,,,,,,,,,,,,,0,,,,,,,,,,,,,,,,0\n...0,,,,,,,,,,,,,,,,,,,,,0,,,,,,,,,,,,,,,,0\n....0,,,,,,,,,,,,,,,,,,,0,,,,,,,,,,,,,,,,0\n.....0,,,,,,,,,,,,,,,,,0,,,,,,,,,,,,,,,0\n```')


@bot.command()
Esempio n. 25
0
import os
import nacl
import discord
import random

from dotenv import load_dotenv
from ytdlsource import YTDLSource
from time import time, sleep
from discord.ext import commands
from ficavivo import keep_alive
from settings import CRAZYFROG_URL, CRAZYFROG_MUSICAS, CRAZYFROG_IMAGES, CRAZYFROG_FRASES, CRAZYFROG_PREFIX

load_dotenv()
intents = discord.Intents(guilds=True,
                          voice_states=True,
                          members=True,
                          messages=True)
bot = commands.Bot(command_prefix=commands.when_mentioned_or(CRAZYFROG_PREFIX),
                   description='Relatively simple music bot example',
                   intents=intents)


@bot.command(pass_context=True)
async def dingding(ctx):
    """Destezo crazy frog"""

    await ctx.channel.send("Destezo crazy frog")


@bot.command(pass_context=False)
async def letra(ctx):
Esempio n. 26
0
support_server_id = 707441352367013899

support_server_invites = {
    "NTRuFjU": "General",
    "xfMZ8q9k3J": "On Patreon",
    "vqHBD3QCv2": "Top.gg",
    "paMxRvvZFc": "On join",
    "XP4avQ449V": "Website",
}

intents = discord.Intents(
    guilds=True,
    voice_states=True,
    messages=True,
    reactions=True,
    members=True,
    bans=True,
    # invites=True,
)

member_cache = discord.MemberCacheFlags(joined=True)

# all_support_ranks = [item for item in support_ranks]

patreon_supporting_role = 843941723041300480


class PremiumTiers:
    free = 0
    tier_1 = 1
Esempio n. 27
0
from player import Player, TsumoBot
from tiles import Tile, Wall, Dora, Hand, Melds, Discards
from graphics import makeImage, makeYamaImage, discard_image
from functions import winning_tiles, ukeire, shanten_calculator
from errorhandling import GameOver

import os
from dotenv import load_dotenv

import discord
from discord.ext import commands

import asyncio

intents = discord.Intents(messages = True, guilds = True, members = True, reactions = True)
discordclient = commands.Bot(command_prefix = 'm!', intents = intents)

load_dotenv()

class Match:
    
    def __init__(self, players, match_id, aka = 3):
        self.match_id = match_id
        self.players = players
        self.player_order = random.sample(players, 4)
        self.round_wind = EAST
        self.round_number = 1
        self.aka = aka
        
    def round_progression(self):
Esempio n. 28
0
import discord
from discord.ext import commands
from keystone import Keystone, KeystoneStorage
from constants import DUNGEON_LIST, DUNGEON_ABBR_LIST, MIN_KEYSTONE_LEVEL, KEYSTONE_ICON_URL, SELF_DESTRUCT_MSG_TIMER

token = open("token.txt", "r").read().strip()

name_len = max(map(lambda name: len(name), DUNGEON_LIST.keys()))
abbr_len = max(map(lambda abbrs: len(', '.join(abbrs)), DUNGEON_LIST.values()))

keystones = KeystoneStorage()

intents = discord.Intents(messages=True, guilds=True)
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!ks '),
                   intents=intents)


@bot.event
async def on_ready():
    print('Logged in as {0.user}'.format(bot))


class AddCommandError(commands.UserInputError):
    def __init__(self, message, arg_string=None, show_cmd_fmt=False):
        add_cmd_fmt = "Expected add command arguments: dungeon level [character]"
        m = message
        if (show_cmd_fmt or arg_string):
            m = "\n".join([message, add_cmd_fmt])
        if (arg_string):
            m = "\n".join([m, "User provided values: {}".format(arg_string)])
        super().__init__(m)
Esempio n. 29
0
import discord
from discord.ext import commands, tasks
from itertools import cycle
import os
import youtube_dl
intents = discord.Intents(messages=True,
                          guilds=True,
                          reactions=True,
                          members=True,
                          presences=True,
                          bans=True,
                          voice_states=True)
client = commands.Bot(command_prefix='+', intents=intents)

status = cycle(['God', 'Life', 'Humans'])


@client.event
async def on_ready():
    await client.change_presence(status=discord.Status.idle)
    change_status.start()
    print('You are logged in as {0.user}'.format(client))


@tasks.loop(seconds=30)
async def change_status():
    await client.change_presence(activity=discord.Game(next(status)))


@client.event
async def on_member_join(member):
Esempio n. 30
0
from cogs.functions.events import Events
from cogs.functions.game_functions import GameFunction
import os
import time
import json
import asyncio
from dislash import InteractionClient
from itertools import cycle
from PIL import Image
from io import BytesIO

from keep_alive import keep_alive
intents = discord.Intents(messages=True,
                          guilds=True,
                          dm_messages=True,
                          members=True,
                          presences=True,
                          dm_reactions=True,
                          reactions=True,
                          emojis=True)
client = commands.Bot(command_prefix=['m! ', 'm!'],
                      case_insensetive=True,
                      help_command=None,
                      intents=intents)
slash = InteractionClient(client)
pfp = cycle(["pick.png", "grass.png", "discomine.jpg"])
profiles = "cogs/functions/main_resources/profiles.json"

events = Func(client)
event = Events(client)
game = GameFunction()