Browse Source

[fix] statusUpdateByDatetime.py should work

master
Alban Crommer 1 year ago
parent
commit
806d932467
2 changed files with 11 additions and 140 deletions
  1. 0
    138
      newTopics.py
  2. 11
    2
      statusUpdateByDatetime.py

+ 0
- 138
newTopics.py View File

@@ -1,138 +0,0 @@
1
-#!/usr/bin/python3
2
-# -*- coding: utf-8 -*-
3
-"""
4
-Updates a mastodon account based on a CSV file containing status 
5
-
6
-Status are defined using 
7
- - date 
8
- - time 
9
- - any number of fields usable in jinja2 templates as variables whose name
10
-   is the column name 
11
-
12
-"""
13
-
14
-import codecs
15
-import csv
16
-from datetime import datetime, timezone
17
-import io
18
-import operator
19
-import os
20
-from os.path import isfile, isdir, dirname, join, realpath
21
-import sys
22
-
23
-# Templates
24
-import jinja2 
25
-
26
-# Toot
27
-from toot.console import main
28
-
29
-# Command line Arguments
30
-from argparse import ArgumentParser
31
-parser = ArgumentParser()
32
-parser.add_argument("-f", "--csv-file", type=str, default="status.csv", help="Which file to use for future status")
33
-parser.add_argument("-a", "--account", type=str, default="default", help="Which name for your bot (if multiple)")
34
-parser.add_argument("-p", "--lastseen-path", type=str, default="/var/cache/newTopics", help="Which path to use for storing ")
35
-parser.add_argument("-pt", "--template-file", type=str, default="template.jinja", help="Which template file to use ")
36
-args = parser.parse_args()
37
-
38
-
39
-def sort_csv(csv_filename):
40
-    """Read and return CSV data sorted by first two fields
41
-    """
42
-    data = []
43
-    global headers
44
-    with open(csv_filename, 'rb') as f:
45
-      for row in csv.reader(codecs.iterdecode(f, 'utf-8'), delimiter=';'):
46
-        if( row[0] == "Date"):
47
-          headers = row
48
-        else:
49
-          data.append( row  )
50
-    data = sorted(data, key = operator.itemgetter(0,1))
51
-    return data
52
-
53
-def recordUpdate():
54
-  """ Helper for updating lastseen 
55
-  """
56
-  handle = open(last_updated_file, 'w')
57
-  handle.write(str(last_updated_at.strftime('%Y-%m-%d %H:%M:%S.%f%z')))
58
-  handle.close()
59
-
60
-# Variables
61
-headers             = []
62
-date_now            = datetime.now(timezone.utc)              # Now()
63
-account             = args.account                            # The tag file lastseen path
64
-lastseen_path       = args.lastseen_path                         # The tag file lastseen path
65
-csv_file            = args.csv_file                           # The status file
66
-template_file       = args.template_file                           # The status file
67
-last_updated_at     = date_now                                # The last time we updated the status
68
-last_updated_file   = join(lastseen_path, "{}.lastseen".format(account))   # lastseen file 
69
-
70
-
71
-templateLoader = jinja2.FileSystemLoader(searchpath="./")
72
-templateEnv = jinja2.Environment(loader=templateLoader)
73
-
74
-
75
-# Exit if lastseen path doesn't exist
76
-if( not isdir( lastseen_path) ):
77
-  print( "Critical error: please create directory {}".format( lastseen_path) )
78
-  os._exit(2)
79
-
80
-
81
-
82
-# Check if csv file exists
83
-if( not isfile( csv_file ) ):
84
-  print("Couldn't find CSV file {}.".format(template_file))
85
-  os._exit(2)
86
-
87
-# Check if template exists
88
-if( not isfile( template_file ) ):
89
-  print("Couldn't find template file {}.".format(template_file))
90
-  os._exit(2)
91
-
92
-# Touch last seen file if not exists
93
-if( isfile( last_updated_file ) ):
94
-  wrapper = open(last_updated_file, 'r',encoding="utf-8")
95
-  try:
96
-    record = next(wrapper)
97
-  except IOError as e:
98
-    print("Couldn't open or write to file (%s)." % e)
99
-  last_updated_at = datetime.strptime(record.rstrip(), '%Y-%m-%d %H:%M:%S.%f%z')
100
-  print( last_updated_at )
101
-else:
102
-  try:
103
-    recordUpdate()
104
-  except IOError as e:
105
-    print("Couldn't open or write to file (%s)." % e)
106
-
107
-# Read CSV file
108
-statusList = sort_csv(csv_file)
109
-
110
-# Walk through records until a date is strictly superior to previous action and inferior to now
111
-for status in statusList: 
112
-  status_date = datetime.strptime("{} {}-+0000".format(status[0],status[1]), '%Y-%m-%d %H:%M:%S-%z')
113
-  status_date.replace(tzinfo=timezone.utc)
114
-
115
-  # Debug
116
-  print( "status:{} last_updated_at:{} now:{}".format(status_date, last_updated_at, date_now) )
117
-
118
-  # Status should be published
119
-  if( status_date > last_updated_at and status_date < date_now ):
120
-    template = templateEnv.get_template(template_file)
121
-    template_vars =  dict(zip(headers, status)) 
122
-    outputText = template.render( template_vars )
123
-
124
-    # Toot 
125
-    sim_args = [sys.argv[0],  'post' ]
126
-
127
-    if ( account ) :
128
-      sim_args.extend( ( '-u', account ))
129
-
130
-    sim_args.append( outputText )
131
-    sys.argv = sim_args
132
-    main()
133
-
134
-    last_updated_at = date_now
135
-    # recordUpdate()
136
-    os._exit(1)
137
-
138
-os._exit(0)

+ 11
- 2
statusUpdateByDatetime.py View File

@@ -71,6 +71,15 @@ last_updated_file   = join(lastseen_path, "{}.lastseen".format(account))   # las
71 71
 templateLoader = jinja2.FileSystemLoader(searchpath="./")
72 72
 templateEnv = jinja2.Environment(loader=templateLoader)
73 73
 
74
+# Exit if csv file does not exist
75
+if( not isfile( csv_file ) ):
76
+  print("Couldn't find CSV file {}.".format(template_file))
77
+  os._exit(2)
78
+
79
+# Exit if template does not exist
80
+if( not isfile( template_file ) ):
81
+  print("Couldn't find template file {}.".format(template_file))
82
+  os._exit(2)
74 83
 
75 84
 # Exit if lastseen path doesn't exist
76 85
 if( not isdir( lastseen_path) ):
@@ -102,7 +111,7 @@ for status in statusList:
102 111
   status_date.replace(tzinfo=timezone.utc)
103 112
 
104 113
   # Debug
105
-  print( "status:{} last_updated_at:{} now:{}".format(status_date, last_updated_at, date_now) )
114
+  # print( "status:{} last_updated_at:{} now:{}".format(status_date, last_updated_at, date_now) )
106 115
 
107 116
   # Status should be published
108 117
   if( status_date > last_updated_at and status_date < date_now ):
@@ -121,7 +130,7 @@ for status in statusList:
121 130
     main()
122 131
 
123 132
     last_updated_at = date_now
124
-    # recordUpdate()
133
+    recordUpdate()
125 134
     os._exit(1)
126 135
 
127 136
 os._exit(0)

Loading…
Cancel
Save