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