我们从Python开源项目中,提取了以下34个代码示例,用于说明如何使用discord.Client()。
def my_background_task(): client = discord.Client() await client.wait_until_ready() channel = discord.Object(id='189472786056478720') feed = youtube.start() while not client.is_closed: update = youtube.update(feed) if update != "304": entry = youtube.getLastEntry() YTEmbed = discord.Embed() YTEmbed.colour = 0x3498db YTEmbed.title = "Nouvelle vidéo sur la chaîne de Sakiut ! `" + entry['title'] + "`" YTEmbed.description = "Vidéo : " + entry['link'] + "\nChaîne : " + entry['channel'] + "\nPosté le : " + entry['published'] YTEmbed.set_thumbnail(url = entry['thumbnail']) YTEmbed.set_footer(text = "Posté par {0}".format(entry['author'])) await client.send_message(channel, "@everyone", embed = YTEmbed) feed = youtube.start() await asyncio.sleep(300)
def send_and_get_rate_limit( client: discord.Client, channel: discord.Channel, content: str ): global global_over global_over = asyncio.Event(loop=asyncio.get_event_loop()) global_over.set() channel_id, guild_id = yield from client._resolve_destination(channel) rate_limit_info = RateLimitInfo() data = yield from send_message(client.http, channel_id, content, rate_limit_info) channel = client.get_channel(data.get('channel_id')) # noinspection PyArgumentList message = client.connection._create_message(channel=channel, **data) return message, rate_limit_info
def _wrap(o, transport): if isinstance(o, list) or isinstance(o, DICT_VALUES): return [_wrap(item, transport) for item in o] elif isinstance(o, tuple): return tuple([_wrap(item, transport) for item in o]) elif isinstance(o, Client): return transport elif isinstance(o, _Server): return DiscordServer(o, transport) elif isinstance(o, _Channel): return DiscordChannel(o, transport) elif isinstance(o, _PrivateChannel): return DiscordChannel(o, transport) elif isinstance(o, _Message): return DiscordMessage(o, transport) elif isinstance(o, _Member): return DiscordWrapper(o, transport) elif isinstance(o, _User): return DiscordWrapper(o, transport) elif isinstance(o, VoiceClient): return DiscordWrapper(o, transport) elif isinstance(o, Enum): return str(o) return o
def notify(self, text, options={}): if 'channel' in options: channel_id = options['channel_id'] else: channel_id = self.channel_id self.client = discord.Client() loop = asyncio.get_event_loop() loop.run_until_complete(self._send_message(channel_id, text)) self.client = None
def on_ready(self): self.out.Success("Client ready! Logged in as " + self.user.id) yield from self.change_presence(game=discord.Game(name='=help for help'))
def __init__(self, client: discord.Client, admins: list = list(), **cfg) -> object: """ Create a ListenerRegistry :param client: the client to use :param admins: the list of admins to use, must be a list of ID's """ self.commands = [] self.logger = logging.getLogger('commandreg') self.logger.setLevel(0) self.client = client self.admins = admins self.muted = [] self.cfg = cfg
def client(self) -> discord.Client: """ The client to use :return: The client, or None if not attached to a registry """ return None if self.registry is None else self.registry.client
def __init__(self, **kwargs): Common.__init__(self) discord.Client.__init__(self, **kwargs) # Modules Bucket self.modules = {} # Event listeners store self._assistant_listeners = {} # Helper function for handling our custom events # noinspection PyBroadException
def set_client(c: discord.Client): """ Assign the client to a variable. """ global client client = c
def convert_image_object(image, format: str="PNG", **params): """ Saves a PIL.Image.Image object to BytesIO buffer. Effectively returns the byte-like object for sending through discord.Client.send_file. :param image: PIL.Image.Image: object to convert. :param format: The image format, defaults to PNG. :param params: Any additional parameters sent to the writer. :return: BytesIO: the image object in bytes. """ buffer = BytesIO() image.save(buffer, format, **params) buffer.seek(0) return buffer
def set_client(c: discord.Client): """ Sets the client. Should be used before any plugins are loaded. """ global client client = c
def __init__(self, token): self.client = discord.Client() self.commands = dict() self.token = token @self.client.event async def on_message(message): split = message.content.split(" ") command = split[0].lstrip("!") if command in self.commands: await self.commands[command](self.client, message, split[1:])
def async_loop(self): self.queue = asyncio.Queue() self.event = asyncio.Event() self.bot = discord.Client() @self.bot.event async def on_ready(): print('Discord component ready!') self.gen_chan = {c.name: c for c in {s.name: s for s in self.bot.guilds}['Codes \'n Skillz Hideout'].channels}['general'] await self.gen_chan.send('**Discordian** GUI started.') await self.bot.start(*token.bot_token) self.loop.stop()
def __init__(self): try: super().__init__() except Exception as e: log.err("Could not initialize client object: " + str(e), "r") else: log.info("Client object initialized") self.config = Config() self.commands = Commands(self) self.members = Members(self) log.info("Configuration object initalized") return
def __init__(self, discord_client: discord.Client, channel: discord.Channel, home_settings: HomeSettings, weather: Weather, message_factory: MessageFactory) -> None: self._discord_client = discord_client self._channel = channel self._home_settings = home_settings self._weather = weather self._message_factory = message_factory
def __init__(self, discord_client: discord.Client, channel: discord.Channel, forecast: WeatherForecast, language: Language, message_factory: MessageFactory) -> None: self._discord_client = discord_client self._channel = channel self._forecast = forecast self._language = language self._message_factory = message_factory
def __init__(self, discord_client: discord.Client, weather: Weather, should_help: bool) -> None: self._discord_client = discord_client self._weather = weather self._should_help = should_help
def __init__(self, discord_client: discord.Client, weather: Weather) -> None: self._discord_client = discord_client self._weather = weather
def __init__(self, application_settings: ApplicationSettings, weather_service: WeatherService, discord_client: discord.Client, message_factory: MessageFactory) -> None: self._application_settings = application_settings self._weather_service = weather_service self._discord_client = discord_client self._message_factory = message_factory
def run(self) -> None: discord_client = discord.Client() weather_service = WeatherService(self._settings.integration_settings.open_weather_map_api_key, self._settings.integration_settings.weather_underground_api_key) message_factory = MessageFactory(self._settings) command_handler = CommandHandler(self._settings, weather_service, discord_client, message_factory) weather_discord_service = WeatherDiscordService(self._settings.measurement_system, self._settings.home_settings, weather_service, discord_client) @discord_client.event async def on_message(message) -> None: await command_handler.handle(message) discord_client.loop.create_task(weather_discord_service.send_home_forecast()) discord_client.loop.create_task(weather_discord_service.update_profile()) discord_client.loop.create_task(weather_discord_service.update_presence()) discord_client.run(self._settings.integration_settings.discord_bot_token)
def __init__(self, token): self.token = token self.bot = None self.client = discord.Client() self.client.on_ready = self.on_ready asyncio.get_event_loop().call_soon(self._report_loop)
def main(): core = Core(discord.Client()) core.run_client()
def __init__(self, loop): CLEAR() self.token = "" self.prefix = "" self.description = "" self.owner_id = "" self.config_file_path = "settings/config.json" self.load_config() self.created_at = None self.total_commands = 0 self.total_runtime = None self.info_file_path = "settings/infos.json" self.load_infos() self.bot = discord.Client() self.default_modules = ["base", "admin"] self.loaded_modules = [] self.modules_file_path = "settings/modules.json" self.blacklist_file_path = "settings/blacklist.json" self.blacklist = [] self.load_blacklist() self.invite_link = "" self.modules = [] self.version = "0.0.1" self.launched_at = datetime.now() super().__init__(command_prefix=self.prefix, description=self.description, loop=loop) CLEAR()
def _setup_client(self): # loop = asyncio.get_event_loop() # loop.slow_callback_duration = 10 self.client = discord.Client() self.client.event(self.on_ready) # ======================================================
def __init__(self, config): self.bot = discord.Client() self.token = config['discordToken'] self.channels = config['mappingChannels'] self.command_chars = config.get('commandChars', []) # signals self.discord_signal = signal(SIGNALNAMES.DISCORD_MSG) self.irc_signal = signal(SIGNALNAMES.IRC_MSG) self.irc_signal.connect(self.on_irc_message) self.bot.event(self.on_message)
def client(self) -> discord.Client: return server.client
def init(client_: discord.Client, server_: discord.Server) -> None: global client, server, main_channel, admin_roles, staff_role client = client_ server = server_ main_channel = server.default_channel for rolename in Config.ADMIN_ROLE_NAMES: for role in server.roles: if role.name == rolename: admin_roles.append(role) if role.name == Config.STAFF_ROLE: staff_role = role
def __init__(self): self.client = discord.Client() self.voice = None
def setUpClass(cls): logging.getLogger("discord").setLevel(logging.ERROR) logging.getLogger("websockets").setLevel(logging.ERROR) bot = discord.Client(fetch_offline_members=False) await bot.login(os.environ['DISCORD_TOKEN']) cls.bot = bot cls.task = asyncio.ensure_future(bot.connect()) await cls.bot.wait_until_ready() cls.channel = bot.get_channel(182580524743655424)
def add_page(self, emoji: str, page: discord.Embed): r""" Adds a page to this PagedEmbed. Arguments: emoji : str A Unicode Emoji like ?? or ??, or the full "text" of a discord Emoji which you can obtain by prepending a \ to the front of a Discord Emoji, resulting in something like this: <:FeelsWOAWMan:273546398996234242> Note, however, that the bot must be able to use the reaction. Since bots have access to Emojis as if they have Nitro, all valid emojis are stored in discord.Client.emojis. page : discord.Embed The discord.Embed which should be displayed when the given Emoji is reacted with / clicked. """ if emoji in self._pages: raise ValueError("A handler or an discord.Embed for this Emoji was already added") self._pages[emoji] = page
def post_login_init( self, client: discord.Client, server_id: int, load_config_fn ) -> None: """Initializes object; call after client has been logged in to discord""" self._load_config_fn = load_config_fn # Find the correct server try: int(server_id) id_is_int = True except ValueError: id_is_int = False the_server = None # type: discord.Server for s in client.servers: if id_is_int and s.id == server_id: the_server = s elif s.name == server_id: the_server = s if the_server is None: console.warning('Could not find the server.') exit(1) server.init(client, the_server) if not self._initted: await self._load_config_fn(self) self._initted = True for manager in self._managers: await manager.initialize() else: await self.refresh() console.info( '\n' '-Logged in---------------\n' ' User name: {0}\n' ' Server name: {1}\n' '-------------------------'.format(the_server.me.display_name, the_server.name) )
def ready_client_events( self, client: discord.Client, load_config_fn: Callable[[], None], on_ready_fn: Callable[[], None] = None ): """Set the code for event-handling in the discord.Client""" @client.event async def on_ready(): """Called after the client has successfully logged in""" await self.post_login_init( client=client, server_id=Config.SERVER_ID, load_config_fn=load_config_fn ) if on_ready_fn is not None: await on_ready_fn(self) @client.event async def on_message(message: discord.Message): """Called whenever a new message is posted in any channel on any server""" if not self._initted: return if Config.testing(): await msgqueue.send_message(message) if message.author.id == self.client.user.id: return cmd = Command(message) await self._execute(cmd) # noinspection PyUnusedLocal @client.event async def on_error(event: str, *args, **kwargs): """Called when an event raises an uncaught exception""" exc_info = sys.exc_info() exc_type = exc_info[0].__name__ if exc_info[0] is not None else '<no exception>' exc_what = str(exc_info[1]) if exc_info[1] is not None else '' console.error( 'Uncaught exception {exc_type}: {exc_what}'.format(exc_type=exc_type, exc_what=exc_what) ) # @client.event # async def on_member_join(member: discord.Member): # """Called when anyone joins the server""" # if not self._initted: # return # # await userdb.register_discord_user(member) # # @client.event # async def on_member_update(member_before: discord.Member, member_after: discord.Member): # """Called when anyone updates their discord profile""" # if not self._initted: # return # # if member_before.display_name != member_after.display_name: # await userdb.register_discord_user(member_after)