本文整理汇总了Python中discord.ext.tasks.loop方法的典型用法代码示例。如果您正苦于以下问题:Python tasks.loop方法的具体用法?Python tasks.loop怎么用?Python tasks.loop使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类discord.ext.tasks
的用法示例。
在下文中一共展示了tasks.loop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: auto_poster_loop
# 需要导入模块: from discord.ext import tasks [as 别名]
# 或者: from discord.ext.tasks import loop [as 别名]
def auto_poster_loop(self) -> None:
"""Post the top 5 posts daily, and the top 5 posts weekly."""
# once we upgrade to d.py 1.3 this can be removed and the loop can use the `time=datetime.time.min` parameter
now = datetime.utcnow()
tomorrow = now + timedelta(days=1)
midnight_tomorrow = tomorrow.replace(hour=0, minute=0, second=0)
seconds_until = (midnight_tomorrow - now).total_seconds()
await asyncio.sleep(seconds_until)
await self.bot.wait_until_guild_available()
if not self.webhook:
await self.bot.fetch_webhook(Webhooks.reddit)
if datetime.utcnow().weekday() == 0:
await self.top_weekly_posts()
# if it's a monday send the top weekly posts
for subreddit in RedditConfig.subreddits:
top_posts = await self.get_top_posts(subreddit=subreddit, time="day")
username = sub_clyde(f"{subreddit} Top Daily Posts")
message = await self.webhook.send(username=username, embed=top_posts, wait=True)
if message.channel.is_news():
await message.publish()
示例2: top_weekly_posts
# 需要导入模块: from discord.ext import tasks [as 别名]
# 或者: from discord.ext.tasks import loop [as 别名]
def top_weekly_posts(self) -> None:
"""Post a summary of the top posts."""
for subreddit in RedditConfig.subreddits:
# Send and pin the new weekly posts.
top_posts = await self.get_top_posts(subreddit=subreddit, time="week")
username = sub_clyde(f"{subreddit} Top Weekly Posts")
message = await self.webhook.send(wait=True, username=username, embed=top_posts)
if subreddit.lower() == "r/python":
if not self.channel:
log.warning("Failed to get #reddit channel to remove pins in the weekly loop.")
return
# Remove the oldest pins so that only 12 remain at most.
pins = await self.channel.pins()
while len(pins) >= 12:
await pins[-1].unpin()
del pins[-1]
await message.pin()
if message.channel.is_news():
await message.publish()
示例3: metric_task
# 需要导入模块: from discord.ext import tasks [as 别名]
# 或者: from discord.ext.tasks import loop [as 别名]
def metric_task(self):
def async_handler(url, method, timeout, headers, data):
async def handle():
async with self.bot.session.request(
method=method,
url=url,
data=data,
headers=headers
) as resp:
if resp.status >= 400:
log.error("Error pushing metrics to gateway: %s %s" % (resp.status, await resp.text()))
return lambda: self.bot.loop.create_task(handle())
log.debug("Pushing metrics to gateway")
try:
prometheus.push_to_gateway(
gateway="prometheus-pushgateway.monitoring:9091",
job=self.bot.config.identifier,
grouping_key={"pod": self.bot.shard_ids[0]},
registry=registry,
handler=async_handler
)
except Exception as e:
log.error("Error pushing metrics to gateway: %s %s" % (type(e), str(e)))
示例4: interval_task
# 需要导入模块: from discord.ext import tasks [as 别名]
# 或者: from discord.ext.tasks import loop [as 别名]
def interval_task(self):
try:
to_backup = self.bot.db.intervals.find({"next": {
"$lt": datetime.utcnow()
}})
semaphore = Semaphore(10)
async for interval in to_backup:
async def run_interval():
try:
next = datetime.utcnow() + timedelta(minutes=interval["interval"])
await self.bot.db.intervals.update_one({"_id": interval["_id"]}, {"$set": {"next": next}})
await self.run_backup(interval["_id"])
finally:
semaphore.release()
await semaphore.acquire()
self.bot.loop.create_task(run_interval())
await sleep(0)
except Exception:
pass
示例5: before_loop_presence
# 需要导入模块: from discord.ext import tasks [as 别名]
# 或者: from discord.ext.tasks import loop [as 别名]
def before_loop_presence(self):
await self.bot.wait_for_connected()
logger.line()
activity, status = await self.set_presence()
if activity is not None:
msg = f"Activity set to: {activity.type.name.capitalize()} "
if activity.type == ActivityType.listening:
msg += f"to {activity.name}."
else:
msg += f"{activity.name}."
logger.info(msg)
else:
logger.info("No activity has been set.")
if status is not None:
msg = f"Status set to: {status.value}."
logger.info(msg)
else:
logger.info("No status has been set.")
await asyncio.sleep(1800)
logger.info("Starting presence loop.")
示例6: startup
# 需要导入模块: from discord.ext import tasks [as 别名]
# 或者: from discord.ext.tasks import loop [as 别名]
def startup(self):
"""Initialize sources and start the loop after initialization"""
self.sources = {}
self.http_source = aiohttp.ClientSession(headers={'Connection': 'keep-alive'})
# Headers to work around JVN's blog... for some reason
for source in self.enabled_sources:
try:
self.sources[source.short_name] = source(aiohttp_session=self.http_source, bot=self.bot)
if issubclass(source, DataBasedSource):
subs = await NewsSubscription.get_by(source=source.short_name)
data = {sub.data for sub in subs}
await self.sources[source.short_name].first_run(data)
else:
await self.sources[source.short_name].first_run()
except ElementTree.ParseError as err:
del self.sources[source.short_name]
DOZER_LOGGER.error(f"Parsing error in source {source.short_name}: {err}")
示例7: __init__
# 需要导入模块: from discord.ext import tasks [as 别名]
# 或者: from discord.ext.tasks import loop [as 别名]
def __init__(self, bot: Bot):
self.bot = bot
self.webhook_names = {}
self.webhook: t.Optional[discord.Webhook] = None
self.bot.loop.create_task(self.get_webhook_names())
self.bot.loop.create_task(self.get_webhook_and_channel())
示例8: __init__
# 需要导入模块: from discord.ext import tasks [as 别名]
# 或者: from discord.ext.tasks import loop [as 别名]
def __init__(self, bot: Bot):
self.bot = bot
self.webhook = None
self.access_token = None
self.client_auth = BasicAuth(RedditConfig.client_id, RedditConfig.secret)
bot.loop.create_task(self.init_reddit_ready())
self.auto_poster_loop.start()
示例9: cog_unload
# 需要导入模块: from discord.ext import tasks [as 别名]
# 或者: from discord.ext.tasks import loop [as 别名]
def cog_unload(self) -> None:
"""Stop the loop task and revoke the access token when the cog is unloaded."""
self.auto_poster_loop.cancel()
if self.access_token and self.access_token.expires_at > datetime.utcnow():
asyncio.create_task(self.revoke_access_token())
示例10: __init__
# 需要导入模块: from discord.ext import tasks [as 别名]
# 或者: from discord.ext.tasks import loop [as 别名]
def __init__(self, bot):
self.bot = bot
self._process_decay_config()
self.queries = self.bot.queries('emotes.sql')
self.tasks = [
self.bot.loop.create_task(meth()) for meth in (
self.find_backend_guilds, self.leave_blacklisted_guilds)]
self.tasks.append(self.decay_loop.start())
self.logger = ObjectProxy(lambda: bot.cogs['Logger'])
self.guild_ids = set()
self.have_guilds = asyncio.Event()
示例11: __init__
# 需要导入模块: from discord.ext import tasks [as 别名]
# 或者: from discord.ext.tasks import loop [as 别名]
def __init__(self, bot):
self.bot = bot
self.bot.is_emoji = self.is_emoji
self.bot.len_emoji = self.len_emoji
self.bot.isascii = lambda s: len(s) == len(s.encode())
self.bot.getperms = self.getperms
self.bot.getguildperms = self.getguildperms
self.bot.ishoisted = self.ishoisted
self.tags = {}
self.reminders = {}
self.bot.loop.create_task(self.loadtags())
self.bot.loop.create_task(self.loadremind())
self.remindcheck.start()
示例12: __init__
# 需要导入模块: from discord.ext import tasks [as 别名]
# 或者: from discord.ext.tasks import loop [as 别名]
def __init__(self, bot):
self.bot = bot
self.recentgban = []
self.bot.load_invites = self.load_invites
self.bot.get_invites = self.get_invites
self.bot.loop.create_task(self.load_aliases())
if not self.bot.dev:
self.refresh_invites.start()
示例13: __init__
# 需要导入模块: from discord.ext import tasks [as 别名]
# 或者: from discord.ext.tasks import loop [as 别名]
def __init__(self, bot):
self.bot = bot
self.mutes = {}
self.bot.loop.create_task(self.load_mutes())
self.tempmute_checker.start()
示例14: __init__
# 需要导入模块: from discord.ext import tasks [as 别名]
# 或者: from discord.ext.tasks import loop [as 别名]
def __init__(self, *args, loop=None, **kwargs):
super().__init__(*args, loop=loop, **kwargs)
self.current_page = {}
self.total_pages = {}
self.continue_paging = {}
示例15: cog_unload
# 需要导入模块: from discord.ext import tasks [as 别名]
# 或者: from discord.ext.tasks import loop [as 别名]
def cog_unload(self):
"""Attempt to gracefully shut down the loop. Doesn't generally work. """
self.get_new_posts.cancel()