python-wechaty icon indicating copy to clipboard operation
python-wechaty copied to clipboard

on_ready()方法中,定时任务 的方法,总是执行两次

Open huangmu168 opened this issue 4 years ago • 8 comments

代码如下:

import os
import re
import time
from datetime import datetime
import asyncio
import random
from typing import List, Optional
from apscheduler.schedulers.asyncio import AsyncIOScheduler

from wechaty import (
	Wechaty, Contact, Friendship, FriendshipType, Message, Room, UrlLink
)

from save_messages import save_wx_messages,save_event_count
#from GetBaoXianDatas import OutPutBaoXianData

from wechaty_puppet import get_logger,MessageType
from wechaty_puppet.schemas.event import EventReadyPayload

logger = get_logger('OurRoomBot')

global user_self

class MyFriendshipBot(Wechaty):
	"""
	listen wechaty event with inherited functions, which is more friendly for
	oop developer
	"""
	def __init__(self):
		super().__init__()
		self.busy = False
		self.auto_reply_comment = "自动回复:忙ing,暂时无法回复,稍后联系您!"

	async def on_friendship(self, friendship: Friendship):
		"""send, receive friend request, and friend confirmation events.

		Args:
			friendship (Friendship): [description]
		"""
		return

	async def on_login(self, contact: Contact):
		print(f'user: {contact} has login')
		global user_self
		user_self = contact


	async def on_ready(self, payload: EventReadyPayload):
		"""All of initialization functions should be done here, eg: get rooms, friends

		Args:
			payload (EventReadyPayload): the ready event data
		"""
		logger.info('do initialization works ...')

		scheduler = AsyncIOScheduler()
		#scheduler.add_job(self.add_friend_by_phone, 'cron', minute='*/3')
		#scheduler.add_job(self.room_say_everyday, 'cron', hour=8, minute=18)
		scheduler.add_job(self.bot_living_say, 'cron', minute='*/20')
		scheduler.start()

	async def bot_living_say(self): 
		"""
		每隔半小时发送一个监控信息
		监测bot是否活跃
		""" 
		lastime = last_admin_say_time()

		if int(time.time())-lastime <10:
			return
			
		our_root = self.Room.load("25053371402@chatroom")
		say_content = "我在运行中[發][發][發]"
		await our_root.say(say_content)

		save_admin_say(	admin_id=user_self.contact_id,
						content=say_content,
						sayTo_id=our_root.room_id
			)

		return

async def main():
	"""Async Main Entry"""
	#将token加入环境变量
	os.environ.setdefault('WECHATY_PUPPET', "wechaty-puppet-hostie") #和getway桥接
	os.environ.setdefault('WECHATY_PUPPET_SERVICE_TOKEN', "753303c5-ca09-4eed-9bfc-5a88d707466f") #这个是自己的token,自己生成那个和getway桥接

	global bot
	
	#bot = MyFriendshipBot().use([DailyPlugin(),MessageTriggerPlugin()]) 
	bot = MyFriendshipBot()
	await bot.start()

if __name__ == '__main__':
	asyncio.run(main())

结果: 2021-04-16 11:40:00,024 - Room - INFO - Room say <我在运行中[發][發][發], None> 2021-04-16 11:40:00,025 - Room - INFO - Room say <我在运行中[發][發][發], None> image

huangmu168 avatar Apr 16 '21 07:04 huangmu168

python版本是3.9 wechaty版本是wechaty-0.7.dev16 image Uploading image.png…

huangmu168 avatar Apr 16 '21 07:04 huangmu168

I can't reproduce your problem which will emit ready event twice. I guess that you should set scheduler as a property to avoid start twice.

Hope that can help you.

wj-Mcat avatar May 05 '21 17:05 wj-Mcat

ping @huangmu168

wj-Mcat avatar May 19 '21 06:05 wj-Mcat

@padlocal I can reproduce the problem steadily, here is my log info:

2021-05-31 00:21:15,502 - Wechaty - INFO - receive <ready> event <EventReadyPayload(data='ready')>
INFO:__main__:ready event
2021-05-31 00:21:20,157 - Wechaty - INFO - receive <ready> event <EventReadyPayload(data='ready')>
INFO:__main__:ready event

wj-Mcat avatar May 30 '21 16:05 wj-Mcat

Add a counter to on_ready, only allowed on_ready to run once

alienfist avatar Aug 26 '21 14:08 alienfist

Add a counter to on_ready, only allowed on_ready to run once

I think it's a temporary issue, you can do it in latest version. I will track it. Thanks for your issue and sharing your great solution.

wj-Mcat avatar Aug 29 '21 10:08 wj-Mcat

My bot's on_ready didn't run!

MrTsien avatar Oct 24 '21 00:10 MrTsien

我用macos启动不执行ready,用centos启动执行两次ready

MrTsien avatar Dec 11 '21 04:12 MrTsien