forked from datacoffee/topicsbot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function.py
More file actions
181 lines (165 loc) · 6.01 KB
/
lambda_function.py
File metadata and controls
181 lines (165 loc) · 6.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import os
import json
import boto3
import urllib3
import gspread
from datetime import datetime
TOKEN = os.environ['TELEGRAM_TOKEN']
CHANNEL = os.environ['NEWS_CHANNEL']
TABLE = os.environ['DYNAMO_TABLE']
BASE_URL = f"https://api.telegram.org/bot{TOKEN}"
GCP_JSON = json.loads(os.environ['GCP_JSON'])
GCP_SPREADSHEET = os.environ['GCP_SPREADSHEET']
GCP_WORKSHEET = os.environ['GCP_WORKSHEET']
GCP_START_ROW = os.environ['GCP_START_ROW']
GCP_DATE_COLUMN = os.environ['GCP_DATE_COLUMN']
GCP_AUTHOR_COLUMN = os.environ['GCP_AUTHOR_COLUMN']
GCP_NEWS_COLUMN = os.environ['GCP_NEWS_COLUMN']
def lambda_handler(event, context):
try:
chat_id = event["message"]["chat"]["id"]
message = event["message"]
if str(chat_id) != CHANNEL:
# response = f"Chat {chat_id} is not allowed"
return {"statusCode": 404}
elif message["text"].startswith("/list"):
response = get_list()
elif message["text"].startswith("/gsheet"):
response = export_to_spreadsheet()
elif message["text"].startswith("/episode "):
response = episode(message)
elif "#news" in message["text"] and message["text"].strip() != "#news":
response = save_news(message)
elif message["text"].startswith("/delete "):
response = delete(message)
if response:
http = urllib3.PoolManager()
s = response
n = 4096
for response_chunk in [s[k:k+n] for k in range(0, len(s), n)]:
data = {
"text": response_chunk,
"chat_id": chat_id,
"parse_mode": 'HTML',
'disable_web_page_preview': True
}
encoded_data = json.dumps(data).encode('utf-8')
url = BASE_URL + "/sendMessage"
resp = http.request('POST',
url,
headers={'Content-Type': 'application/json'},
body=encoded_data)
except Exception as e:
print(f"An error occurred: {e}")
return {"statusCode": 200}
def get_list():
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(TABLE)
key = boto3.dynamodb.conditions.Key('episode').eq('next')
items = table.query(
KeyConditionExpression=key
)
response = 'News'
for authors in items['Items']:
response += f"\n from @{authors['author']}"
for item in authors['news']:
response += f"\n- {item['added']}, {item['text']}"
response += ''
return response
def export_to_spreadsheet():
try:
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(TABLE)
key = boto3.dynamodb.conditions.Key('episode').eq('next')
items = table.query(
KeyConditionExpression=key
)
gc = gspread.service_account_from_dict(GCP_JSON)
sh = gc.open(GCP_SPREADSHEET)
worksheet = sh.worksheet(GCP_WORKSHEET)
current_row = int(GCP_START_ROW)
for authors in items['Items']:
for item in authors['news']:
worksheet.update(f'{GCP_DATE_COLUMN}{str(current_row)}', item['added'])
worksheet.update(f'{GCP_AUTHOR_COLUMN}{str(current_row)}', f"@{authors['author']}")
worksheet.update(f'{GCP_NEWS_COLUMN}{str(current_row)}', item['text'])
current_row += 1
response = 'News list was exported to Google spreadsheet'
except Exception as e:
response = f'Error: {e}'
return response
def save_news(message):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(TABLE)
item = table.get_item(
Key={
"episode": "next",
"author": message["from"]["username"]
}
)
if 'Item' in item:
item = item['Item']
item['news'].append(
{
"added": datetime.now().strftime("%m/%d/%Y, %H:%M:%S"),
"text": message["text"].replace('#news', '')
}
)
else:
item = {
"episode": "next",
"author": message["from"]["username"],
"news": [
{
"added": datetime.now().strftime("%m/%d/%Y, %H:%M:%S"),
"text": message["text"].replace('#news', '')
}
]
}
resp = table.put_item(Item=item)
if "ResponseMetadata" in resp.keys() and resp["ResponseMetadata"]["HTTPStatusCode"] == 200:
response = "Saved!"
else:
print(resp)
response = "Saving Error!"
return response
def episode(message):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(TABLE)
key = boto3.dynamodb.conditions.Key('episode').eq('next')
items = table.query(
KeyConditionExpression=key
)
ep_num = message['text'].replace("/episode ", '')
if ep_num.strip() == '':
response = 'Episode # must be specified'
for item in items['Items']:
table.delete_item(
Key={
"episode": item['episode'],
"author": item['author']
}
)
item['episode'] = ep_num
table.put_item(Item=item)
response = f'News saved for episode #{ep_num}'
return response
def delete(message):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(TABLE)
key = boto3.dynamodb.conditions.Key('episode').eq('next')
items = table.query(
KeyConditionExpression=key
)
response = ''
for authors in items['Items']:
for item in authors['news']:
if item['added'] == message["text"].replace('/delete ', ''):
response += 'Deleted: ' + item['text'] + '\n'
authors['news'].remove(item)
resp = table.put_item(Item=authors)
if "ResponseMetadata" in resp.keys() and resp["ResponseMetadata"]["HTTPStatusCode"] == 200:
response += "Done!"
else:
response = "Can't save changes!"
return response