fbchat-dev/fbchat

Script hangs until Ctrl+C is clicked

Open

#520 创建于 2020年1月23日

在 GitHub 查看
 (9 评论) (0 反应) (0 负责人)Python (406 fork)github user discovery
bughelp wanted

仓库指标

Star
 (1,210 star)
PR 合并指标
 (PR 指标待抓取)

描述

Description of the problem

My Script hangs on when Listening until I click ctrl+c which resumes it. There is not trace when it happens

Code to reproduce


import configparser
from fbchat import log, Client, Message, Plan
from icalendar import Calendar, Event
from datetime import datetime
import time
from pytz import UTC # timezone
from itertools import islice
import requests
import re
import json
import os


#https://fbchat.readthedocs.io/en/stable/examples.html




#mainFunction that calls the rest

def invitedToThread(thread_id):
    if hasMessagedThread(thread_id):
        client.send(Message(text='Hi Team, I am here to automatically create your Facebook Event Plan for all of your games! To start please type "Register Bot TEAMNAME" without the quotes replacing TEAMNAME with your team name as shown on dodgeballwinnipeg.com'), thread_id=thread_id, thread_type=thread_type)
        logThread(thread_id)
    
def logThread(thread_id):
    f = open(dirpath +"/threads.txt", "a")
    f.write(thread_id)
    f.close()
def hasMessagedThread(thread_id):
    with open(dirpath +'/threads.txt') as f:
        if thread_id in f.read():
            return True
        else:
            return False

#grab calendar ICS from URL defined in config file
def grabCalendar():
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
    req = requests.get(config['CALENDAR']['URL'],headers=headers )
    data = req.text
    print("Calendar Retrieved")
    return(data)
    
#Loop through calendar events
def calendarEventCreate(g,client):
    gcal = Calendar.from_ical(g)
    numberOfTeams = 0;
    teamsProcessed = -1;
    teams = list(config['TEAMS'].keys());
    length = len(teams) 
     
    n = length
    m = 3
    teamObj = [[0] * m for i in range(n)]
    for i in range(length): 
        teamObj[i][0] = teams[i]
        teamObj[i][1]= config['TEAMS'][teams[i]]
        teamObj[i][2] = False
        numberOfTeams = i
    #loop through all ics events
    for event in gcal.walk('vevent'):
        start = event.get('dtstart')
        summary = event.get('summary')
        location = event.get('location')
        #event is before today
        if(start.dt < datetime.now()):
            print("Before")
        else:
        #future event
            for team in teamObj: 
                #match team name in calendar and the fact that the team hasnt been processed already
                if(re.search(team[0], summary, re.IGNORECASE)and team[2] == False):
                    createFBPlan(team[1],start.dt,summary,location,client)
                    team[2] = True
                    teamsProcessed += 1
                    #once all teams have been processed then break function
                    if teamsProcessed == numberOfTeams:
                        return

#creatae FB Plan in thread 
def createFBPlan(threadid, dt, summary, eventlocation,client):
    #try:
    print(summary)
    plantime = (time.mktime(dt.timetuple()))
    theplan = Plan( time=plantime, title=summary, location=eventlocation)
    client.createPlan(theplan,thread_id=threadid)
    print("Created FBPlan for " + summary)
    client.changePlanParticipation(theplan,take_part = False)
    #except:
        #print("Error creating FBPlan")


# Subclass fbchat.Client and override required methods
class EchoBot(Client):
    def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):
        self.markAsDelivered(thread_id, message_object.uid)
        self.markAsRead(thread_id)
        # If you're not the author, echo
        if author_id != self.uid:
            if "Register Bot" in message_object.text:
                print("Register Team")
                team_name = message_object.text.split("Register Bot",1)[1]
                config["TEAMS"][team_name.strip()] = thread_id
                with open(dirpath+'/configdraft.ini', 'w') as configfile:
                    config.write(configfile)
                self.send(Message(text='Your team has now been registered, you should see a Facebook Plan created the when one doesnt exist.'), thread_id=thread_id, thread_type=thread_type)
                data = grabCalendar()
                time.sleep(5)
                calendarEventCreate(data,self)
            else:
                print("Invited to Thread")
                if hasMessagedThread(thread_id) == False:
                    self.send(Message(text='Hi Team, I am here to automatically create your Facebook Event Plan for all of your games! To start please type "Register Bot TEAMNAME" without the quotes replacing TEAMNAME with your team name'), thread_id=thread_id, thread_type=thread_type)
                    logThread(thread_id)
    def onPlanCreated(
        self,
        mid=None,
        plan=None,
        author_id=None,
        thread_id=None,
        thread_type=None,
        ts=None,
        metadata=None,
        msg=None,
    ):
        """Called when the client is listening, and somebody creates a plan.

        Args:
            mid: The action ID
            plan (Plan): Created plan
            author_id: The ID of the person who created the plan
            thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
            thread_type (ThreadType): Type of thread that the action was sent to. See :ref:`intro_threads`
            ts: A timestamp of the action
            metadata: Extra metadata about the action
            msg: A full set of the data received
        """
        log.info(
            "{} created plan {} in {} ({})".format(
                author_id, plan, thread_id, thread_type.name
            )
        )
        self.changePlanParticipation(plan,take_part = False)
    def onPlanEnded(
        self,
        mid=None,
        plan=None,
        thread_id=None,
        thread_type=None,
        ts=None,
        metadata=None,
        msg=None,
    ):
        """Called when the client is listening, and a plan ends.

        Args:
            mid: The action ID
            plan (Plan): Ended plan
            thread_id: Thread ID that the action was sent to. See :ref:`intro_threads`
            thread_type (ThreadType): Type of thread that the action was sent to. See :ref:`intro_threads`
            ts: A timestamp of the action
            metadata: Extra metadata about the action
            msg: A full set of the data received
        """
        log.info(
            "Plan {} has ended in {} ({})".format(plan, thread_id, thread_type.name)
        )
        print("Start Grab Calendar")
        data = grabCalendar()
        time.sleep(5)
        calendarEventCreate(data,self)
                
dirpath = os.path.dirname(os.path.abspath(__file__))           
#grabs config and calls main function
config = configparser.ConfigParser()
config.read(dirpath+'/configdraft.ini')

cookies = {}
try:
    # Load the session cookies
    with open(dirpath+'/sessiondraft.json', 'r') as f:
        cookies = json.load(f)
except:
    # If it fails, never mind, we'll just login again
    pass

client = EchoBot(config['FACEBOOK']['facebookemail'], config['FACEBOOK']['facebookpassword'],session_cookies=cookies)
with open(dirpath+'/sessiondraft.json', 'w') as f:
    json.dump(client.getSession(), f)

client.listen()





Environment information

  • Python version 3.6.7
  • fbchat version 1.9.6
  • If relevant, output from $ python -m pip list

If you have done any research, include that. Make sure to redact all personal information.

贡献者指南