Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Command chatsaver archives a Facebook Messenger chat
- // history as a file for github.com/unixpickle/chatbot.
- package main
- import (
- "encoding/csv"
- "fmt"
- "os"
- "strings"
- "github.com/howeyc/gopass"
- "github.com/unixpickle/fbmsgr"
- )
- func main() {
- fmt.Print("Email/username: ")
- user := readLine()
- fmt.Print("Password: ")
- pass, err := gopass.GetPasswdMasked()
- if err != nil {
- fmt.Fprintln(os.Stderr, err)
- os.Exit(1)
- }
- fmt.Println()
- fmt.Println("Authenticating...")
- sess, err := fbmsgr.Auth(user, string(pass))
- if err != nil {
- fmt.Fprintln(os.Stderr, "Failed to login:", err)
- os.Exit(1)
- }
- fbid := promptChat(sess)
- fmt.Print("Destination filename: ")
- file := readLine()
- fmt.Println("Downloading messages...")
- var outRows [][]string
- actionChan, errChan := sess.FullActionLog(fbid, nil)
- for action := range actionChan {
- if msg, ok := action.(*fbmsgr.MessageAction); ok {
- if msg.AuthorFBID() == sess.FBID() {
- outRows = append(outRows, []string{"bot", msg.Body})
- } else {
- outRows = append(outRows, []string{"human", msg.Body})
- }
- fmt.Printf("\rGot %d messages...", len(outRows))
- }
- }
- fmt.Printf("\rTotal of %d messages...\n", len(outRows))
- if err := <-errChan; err != nil {
- fmt.Fprintln(os.Stderr, "Fetch error:", err)
- }
- for i := 0; i < len(outRows)/2; i++ {
- outRows[i], outRows[len(outRows)-(i+1)] = outRows[len(outRows)-(i+1)], outRows[i]
- }
- outFile, err := os.Create(file)
- if err != nil {
- fmt.Fprintln(os.Stderr, "Create output:", err)
- os.Exit(1)
- }
- w := csv.NewWriter(outFile)
- err = w.WriteAll(outRows)
- outFile.Close()
- if err != nil {
- fmt.Fprintln(os.Stderr, "Write output:", err)
- os.Exit(1)
- }
- }
- func promptChat(s *fbmsgr.Session) string {
- fmt.Println("Listing your chats...")
- var idx int
- for {
- listing, err := s.Threads(idx, 20)
- if err != nil {
- fmt.Fprintln(os.Stderr, "Failed to list threads:", err)
- os.Exit(1)
- }
- for _, entry := range listing.Threads {
- otherNames := []string{}
- for _, id := range entry.Participants {
- for _, person := range listing.Participants {
- if person.FBID == id {
- otherNames = append(otherNames, person.Name)
- }
- }
- }
- names := strings.Join(otherNames, ",")
- if entry.Name == "" {
- fmt.Println(entry.ThreadFBID, "with", names)
- } else {
- fmt.Printf("%s named %s (with %s)\n", entry.ThreadFBID, entry.Name, names)
- }
- }
- if len(listing.Threads) < 20 {
- break
- }
- idx += len(listing.Threads)
- }
- fmt.Print("Pick FBID: ")
- return readLine()
- }
- func readLine() string {
- var res string
- for {
- buf := make([]byte, 1)
- if n, err := os.Stdin.Read(buf); err != nil {
- break
- } else if n != 0 {
- if buf[0] == '\n' {
- break
- }
- res += string(buf[0])
- }
- }
- return res
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement