· 6 years ago · Apr 03, 2020, 06:34 PM
1import vk_api, requests, time
2from telebot import types
3import os
4from flask import Flask, request
5from telebot import apihelper
6import telebot
7import re, csv, random
8import threading
9from datetime import datetime,timedelta
10import apiai, json
11import lastdaymonthmodul
12from emoji import emojize
13from dbmbot import init_db, add_user_id_and_message_id, verify_user, get_summ, add_autor_id, get_autor_id, get_great_foto,delete_from_date, add_user_chat_id,get_user_chat_id
14
15
16server = Flask(__name__)
17URL = os.getenv("URL") # Ничего не трогать!
18TOKEN = os.getenv("TOKEN") # Здесь тоже!
19
20bot = telebot.TeleBot(TOKEN, threaded=False)
21vk = vk_api.VkApi(token='f5b07c111......................')
22print(bot.get_me())
23
24
25def check_id_post(text_autor=''):
26 with open('id_post_text.txt', 'r',encoding='UTF-8') as text:
27 post_id=text.readlines()
28 print(post_id)
29 if text_autor!=post_id[0]:
30 return True
31 else:
32 return False
33
34
35def check_pinned(): # проверить запись
36 time.sleep(0.35)
37 is_pinned=vk.method('wall.get', {'owner_id': -78985442, 'count': 1, 'filter':'owner', 'offset':0})['items'][0]['is_pinned']
38 if is_pinned==1: return 1
39 return 0
40
41
42def get_wall_post(): # получить пост из ВК
43 offset=check_pinned()
44 info_wall = vk.method('wall.get', {'owner_id': -78985442, 'count': 1, 'filter':'owner', 'offset':offset})['items'][0]
45 time.sleep(0.35)
46 info_autor=info_wall['text']
47 id_post_text = str(info_wall['id'])
48 info_attachments=info_wall["attachments"][0]['photo']['sizes'][-1]['url']
49 if check_id_post(id_post_text):
50 save_photo(info_attachments)
51 save_post_id_vk(id_post_text=id_post_text)
52 save_text(info_autor)
53 print(info_autor)
54 return info_autor
55 else:
56 return False
57
58
59def save_photo(info_attachments): # запись фотографии со стены группы в ВК
60 img_data = requests.get(str(info_attachments))
61 with open('file_place_name.jpg', 'wb') as photo:
62 photo.write(img_data.content)
63
64
65def save_text(info_autor=''): # запись текста в файл с поста ВК
66 autor_link=re.findall(r'htt(.+)', info_autor)
67 autor_link[0]='htt'+autor_link[0]
68 info_autor=info_autor.replace(autor_link[0],'')
69 autor_link.append(info_autor)
70 with open('post_m_text.txt', 'w', encoding='UTF-8') as text:
71 for element in autor_link:
72 text.write(element)
73 text.write('\n')
74
75
76def save_post_id_vk(id_post_text=''): # запись id в файл с поста ВК
77 with open('id_post_text.txt', 'w', encoding='UTF-8') as text:
78 text.write(id_post_text)
79
80
81def send_new_posts(): # отправка сообщение в канала телеграмма
82 autor=get_wall_post()
83 if autor!=False:
84 with open('post_m_text.txt', 'r',encoding='UTF-8') as text:
85 mes=text.readlines()
86 with open('file_place_name.jpg', 'rb') as photo:
87 count=[0,0]
88 keyboard=create_new_keyboard(autor_id=str(mes[0]))
89 res=bot.send_photo(-1001238583708, photo, caption=mes[1], reply_markup=keyboard)
90 add_autor_id(autor_id=str(mes[0]), message_id=res.message_id, data_time=datetime.now().date())
91 print('сообщение отправил')
92 else:
93 pass
94
95
96def create_new_keyboard(count=[0,0], autor_id=''):
97 keyboard = types.InlineKeyboardMarkup(row_width=2)
98 like_button = types.InlineKeyboardButton(text=f"? +{str(count[0])}", callback_data='like')
99 dislike_button = types.InlineKeyboardButton(text=f"?? -{str(count[1])}", callback_data='dislike')
100 keyboard.add(like_button, dislike_button)
101 to_tell = types.InlineKeyboardButton(text='Рассказать друзьям',
102 url='https://telegram.me/share/url?url=https://t.me/magellando')
103 to_autor = types.InlineKeyboardButton(text='Связаться с автором', url=autor_id)
104 to_link_a = types.InlineKeyboardButton(text='Подобрать Авиабилет', url='http://www.aviasales.ru/?marker=276711')
105 keyboard.add(to_tell)
106 keyboard.add(to_autor)
107 keyboard.add(to_link_a)
108 return keyboard
109
110
111@bot.callback_query_handler(func=lambda call: call.data and call.data in ['like', 'dislike'])
112def query_handler(call):
113 if call.data == 'like':
114 user_id = call.from_user.id
115 message_id=call.message.message_id
116 like=True
117 if verify_user(user_id=user_id, message_id=message_id):
118 bot.answer_callback_query(callback_query_id=call.id, text='Вы уже голосовали за эту фотографию!', show_alert=False)
119 else:
120 add_user_id_and_message_id(user_id=user_id, message_id=message_id, like=like, data_time=datetime.now().date())
121 count=get_summ(message_id=message_id)
122 autor_id=get_autor_id(message_id=message_id)
123 bot.edit_message_reply_markup(chat_id=call.message.chat.id, message_id=call.message.message_id,
124 reply_markup=create_new_keyboard(count=count, autor_id=autor_id[0]))
125 bot.answer_callback_query(callback_query_id=call.id, text='Вы поставили лайк!', show_alert=False)
126 elif call.data == 'dislike':
127 user_id = call.from_user.id
128 message_id = call.message.message_id
129 like = False
130 if verify_user(user_id=user_id, message_id=message_id):
131 bot.answer_callback_query(callback_query_id=call.id, text='Вы уже голосовали за эту фотографию!', show_alert=False)
132 else:
133 add_user_id_and_message_id(user_id=user_id, message_id=message_id, like=like, data_time=datetime.now().date())
134 count = get_summ(message_id=message_id)
135 autor_id = get_autor_id(message_id=message_id)
136 bot.edit_message_reply_markup(chat_id=call.message.chat.id, message_id=call.message.message_id,
137 reply_markup=create_new_keyboard(count=count, autor_id=autor_id[0]))
138 bot.answer_callback_query(callback_query_id=call.id, text='Вы поставили дизлайк!', show_alert=False)
139
140
141@bot.message_handler(commands=['start'])
142def start(message):
143 bot.send_message(message.from_user.id, 'Салют. Географ Фернан Магеллан с поддержкой ИИ к вашим услугам.'
144 '\nУ меня вы можете узнать: '
145 '\n1. Как делать фотографии уникальных природных объектов.'
146 '\n2. Куда лучше отправиться в путешествие в текущем сезоне.'
147 '\n3. Найти недорогие билеты для путешествий.'
148 '\n Я умею работать в режиме искусственного интеллекта, с его помощью '
149 '\n вы можете поговорить со мной в свободной форме обмениваясь сообщениями.'
150 '\n Первые три пункта при этом можно выбрать из стандартного меню.'
151 '\n Введите для продолжения /help.')
152 add_user_chat_id(user_id=message.from_user.id, chat_id=message.chat.id)
153
154
155@bot.message_handler(commands=['help'])
156def help_msg(message):
157 request = apiai.ApiAI('a6526b4fdc..............').text_request() # Токен API к Dialogflow
158 request.lang = 'ru' # На каком языке будет послан запрос
159 request.session_id = 'Mogellanbot' # ID Сессии диалога (нужно, чтобы потом учить бота)
160 request.query = 'хей' # Посылаем запрос к ИИ с сообщением от юзера
161 responseJson = json.loads(request.getresponse().read().decode('utf-8'))
162 response = responseJson['result']['fulfillment']['speech'] # Разбираем JSON и вытаскиваем ответ
163 bot.send_message(message.chat.id, response)
164 keyboardmain = types.InlineKeyboardMarkup(row_width=2)
165 foto_info_button = types.InlineKeyboardButton(text="Съемка пейзажей", callback_data="foto_info")
166 observation_button = types.InlineKeyboardButton(text="Интересные места", callback_data="geo")
167 calendar_button = types.InlineKeyboardButton(text="Недорогие билеты", callback_data="astrocalendar")
168 keyboardmain.add(foto_info_button, observation_button)
169 keyboardmain.add(calendar_button)
170 bot.send_message(message.chat.id, "Выбери, что интересно узнать из стандартного меню.", reply_markup=keyboardmain)
171
172
173@bot.message_handler(commands=['greatphoto'])
174def get_interval_date(message):
175 dt=datetime.now().date()
176 if dt.month==1:
177 year_past = dt.year - 1
178 dt = str(dt.replace(month=12,year=year_past))
179 else:
180 pastmonth = dt.month - 1
181 dt = str(dt.replace(month=pastmonth))
182 star_dt=lastdaymonthmodul.get_first_day_of_month( dt )
183 end_dt=lastdaymonthmodul.get_last_day_of_month( dt )
184 bot.send_message(message.chat.id, 'Лучшие фотографы за месяц')
185 links=get_great_foto(start_dt=star_dt, end_dt=end_dt)
186 for i in range(len(links)):
187 bot.send_message(message.chat.id, links[i][1])
188
189
190@bot.message_handler(commands=['deletebd'])
191def delete_bd(message):
192 dt=datetime.now().date()
193 if dt.month==1:
194 year_past = dt.year-1
195 dt = str(dt.replace(month=10, year=year_past))
196 elif dt.month==2:
197 year_past = dt.year - 1
198 dt = str(dt.replace(month=11, year=year_past))
199 elif dt.month==3:
200 year_past = dt.year - 1
201 dt = str(dt.replace(month=12, year=year_past))
202 else:
203 pastmonth = dt.month - 3
204 dt = str(dt.replace(month=pastmonth))
205 star_dt=lastdaymonthmodul.get_first_day_of_month( dt )
206 end_dt=lastdaymonthmodul.get_last_day_of_month( dt )
207 bot.send_message(message.chat.id, 'Записи удалил')
208 links=delete_from_date(start_dt=star_dt, end_dt=end_dt)
209
210
211@bot.message_handler(commands=["newsletter"])
212def answer(message):
213 if (message.from_user.id == 479715437):
214 newsletter = message.text.split(maxsplit=1)[1]
215 allusers=get_user_chat_id()
216 for i in range(len(allusers)):
217 try:
218 if i % 10 == 0:
219 time.sleep(1)
220 bot.send_message(allusers[i][0], newsletter)
221 except:
222 continue
223
224
225def get_text_travel():
226 columns_dict = dict()
227 with open('maginfo.csv', 'r', encoding='utf-8') as resultFile:
228 reader = csv.DictReader(resultFile, delimiter=';')
229 for col_name in reader.fieldnames:
230 columns_dict[col_name] = []
231 for row in reader:
232 for col_name in reader.fieldnames:
233 columns_dict[col_name].append(row[col_name])
234 columns_dict['европа'] = columns_dict.pop('\ufeffeвропа')
235 for key in columns_dict.keys():
236 columns_dict[key] = [i.rstrip() for i in columns_dict[key] if i != '']
237 return columns_dict
238
239
240def get_text_foto():
241 columns_dict = dict()
242 with open('foto_view.csv', 'r', encoding='utf-8') as resultFile:
243 reader = csv.DictReader(resultFile, delimiter=';')
244 for col_name in reader.fieldnames:
245 columns_dict[col_name] = []
246 for row in reader:
247 for col_name in reader.fieldnames:
248 columns_dict[col_name].append(row[col_name])
249 return columns_dict
250
251
252def get_foto(key=''):
253 return random.SystemRandom().choice(get_text_foto()[key])
254
255
256def get_place(key=''):
257 return random.SystemRandom().choice(get_text_travel()[key])
258
259
260@bot.message_handler(content_types=['text'])
261def reply_massage(message):
262 request = apiai.ApiAI('a6526b4fdcff433499a0940e756e24bc').text_request() # Токен API к Dialogflow
263 request.lang = 'ru' # На каком языке будет послан запрос
264 request.session_id = 'Mogellanbot' # ID Сессии диалога (нужно, чтобы потом учить бота)
265 request.query = message.text # Посылаем запрос к ИИ с сообщением от юзера
266 responseJson = json.loads(request.getresponse().read().decode('utf-8'))
267 response = responseJson['result']['fulfillment']['speech'] # Разбираем JSON и вытаскиваем ответ
268 bot.send_message(message.chat.id, response)
269
270
271@bot.callback_query_handler(func=lambda call:call.data and call.data in
272 ['mainmenu', 'foto_info', 'geo','astrocalendar', 'europe',
273 'nordAm','southAm', 'australia','asia','africa','foto_nature','foto_night'])
274def callback_inline(call):
275 if call.data == "mainmenu":
276 keyboardmain = types.InlineKeyboardMarkup(row_width=2)
277 foto_info_button = types.InlineKeyboardButton(text="Съемка пейзажей", callback_data="foto_info")
278 observation_button = types.InlineKeyboardButton(text="Интересные места", callback_data="geo")
279 calendar_button = types.InlineKeyboardButton(text="Недорогие билеты", callback_data="hostel_info")
280 keyboardmain.add(foto_info_button, observation_button)
281 keyboardmain.add(calendar_button)
282 bot.edit_message_text(chat_id=call.message.chat.id,message_id=call.message.message_id, text="Главное меню",reply_markup=keyboardmain)
283
284
285 if call.data == "foto_info":
286 bot.send_message(chat_id=call.message.chat.id, text='Выберите тип объекта съемки')
287 keyboard = types.InlineKeyboardMarkup(row_width=2)
288 foto_info_nature = types.InlineKeyboardButton(text="Съемка дневного пейзажа", callback_data="foto_nature")
289 foto_info_night = types.InlineKeyboardButton(text="Съемка ночного пейзажа", callback_data="foto_night")
290 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
291 keyboard.add(foto_info_nature)
292 keyboard.add(foto_info_night)
293 keyboard.add(backbutton)
294 bot.send_message(chat_id=call.message.chat.id, text="Объект съемки:",reply_markup=keyboard)
295
296
297 elif call.data == "geo":
298 bot.send_message(chat_id=call.message.chat.id,text='Выберите материк')
299 keyboard = types.InlineKeyboardMarkup(row_width=2)
300 europe_button = types.InlineKeyboardButton(text="Европа",callback_data="europe")
301 asia_button = types.InlineKeyboardButton(text="Азия", callback_data="asia")
302 africa_button = types.InlineKeyboardButton(text="Африка", callback_data="africa")
303 nordAm_button = types.InlineKeyboardButton(text="Северная Америка", callback_data="nordAm")
304 southAm_button = types.InlineKeyboardButton(text="Южная Америка", callback_data="southAm")
305 australia_button = types.InlineKeyboardButton(text="Австралия", callback_data="australia")
306 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
307 keyboard.add(asia_button, europe_button)
308 keyboard.add(southAm_button)
309 keyboard.add(nordAm_button)
310 keyboard.add(africa_button)
311 keyboard.add(australia_button)
312 keyboard.add(backbutton)
313 bot.send_message(chat_id=call.message.chat.id, text="Объект съемки: ", reply_markup=keyboard)
314
315
316 elif call.data == "foto_night":
317 keyboard = types.InlineKeyboardMarkup()
318 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
319 yet_place = types.InlineKeyboardButton(text="Узнать еще", callback_data="foto_info")
320 keyboard.add(backbutton)
321 keyboard.add(yet_place)
322 key='Съемка ночного пейзажа'
323 bot.send_message(chat_id=call.message.chat.id, text=get_foto(key=key), reply_markup=keyboard)
324
325
326 elif call.data == "foto_nature":
327 keyboard = types.InlineKeyboardMarkup()
328 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
329 yet_place = types.InlineKeyboardButton(text="Узнать еще", callback_data="foto_info")
330 keyboard.add(backbutton)
331 keyboard.add(yet_place)
332 key='Съемка дневного пейзажа'
333 bot.send_message(chat_id=call.message.chat.id, text=get_foto(key=key), reply_markup=keyboard)
334
335
336 elif call.data == "europe":
337 keyboard = types.InlineKeyboardMarkup()
338 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
339 yet_place = types.InlineKeyboardButton(text="Еще место", callback_data="geo")
340 keyboard.add(backbutton)
341 keyboard.add(yet_place)
342 key='европа'
343 bot.send_message(chat_id=call.message.chat.id, text=get_place(key=key), reply_markup=keyboard)
344
345
346 elif call.data == "asia":
347 keyboard = types.InlineKeyboardMarkup()
348 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
349 yet_place = types.InlineKeyboardButton(text="Еще место", callback_data="geo")
350 keyboard.add(backbutton)
351 keyboard.add(yet_place)
352 key='азия'
353 bot.send_message(chat_id=call.message.chat.id, text=get_place(key=key), reply_markup=keyboard)
354
355
356 elif call.data == "southAm":
357 keyboard = types.InlineKeyboardMarkup()
358 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
359 yet_place = types.InlineKeyboardButton(text="Еще место", callback_data="geo")
360 keyboard.add(backbutton)
361 keyboard.add(yet_place)
362 key='южная америка'
363 bot.send_message(chat_id=call.message.chat.id, text=get_place(key=key), reply_markup=keyboard)
364
365
366 elif call.data == "nordAm":
367 keyboard = types.InlineKeyboardMarkup()
368 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
369 yet_place = types.InlineKeyboardButton(text="Еще место", callback_data="geo")
370 keyboard.add(backbutton)
371 keyboard.add(yet_place)
372 key='северная америка'
373 bot.send_message(chat_id=call.message.chat.id, text=get_place(key=key), reply_markup=keyboard)
374
375
376 elif call.data == "africa":
377 keyboard = types.InlineKeyboardMarkup()
378 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
379 yet_place = types.InlineKeyboardButton(text="Еще место", callback_data="geo")
380 keyboard.add(backbutton)
381 keyboard.add(yet_place)
382 key='африка'
383 bot.send_message(chat_id=call.message.chat.id, text=get_place(key=key), reply_markup=keyboard)
384
385
386 elif call.data == "australia":
387 keyboard = types.InlineKeyboardMarkup()
388 backbutton = types.InlineKeyboardButton(text="Назад", callback_data="mainmenu")
389 yet_place = types.InlineKeyboardButton(text="Еще место", callback_data="geo")
390 keyboard.add(backbutton)
391 keyboard.add(yet_place)
392 key='австралия'
393 bot.send_message(chat_id=call.message.chat.id, text=get_place(key=key), reply_markup=keyboard)
394
395
396def run_post():
397 threading.Timer(300.0, run_post).start()
398 send_new_posts()
399
400
401# Здесь вообще не трогать!
402@server.route('/' + TOKEN, methods=['POST'])
403def getMessage():
404 bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode("utf-8"))])
405 return "!", 200
406
407
408@server.route("/")
409def webhook():
410 bot.remove_webhook()
411 bot.set_webhook(url=URL + TOKEN)
412 return "!", 200
413
414
415if __name__ == "__main__":
416 init_db()
417 run_post()
418 server.run(host="0.0.0.0", port=int(os.environ.get('PORT', 5000)))