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)
python类Client()的实例源码
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 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 client(self) -> discord.Client:
return server.client
def __init__(self):
self.client = discord.Client()
self.voice = None