def telegram_chatbot(request, token_in): print(request.body) body = request.body body = body.decode('utf-8') jsonbody = json.loads(body) # print(type(json.loads(body))) chat_id = '' text = '' try: chat_id = jsonbody.get('message').get('from').get('id') text = jsonbody.get('message').get('text') if '/start' in text: print('start') sendtext = "환영합니다 !\n" sendtext += "뭐먹을까 ChatBot 입니다\n" sendtext += "점심시간에 맛집 정보를 추천하고 맛집 검색 서비스를 해드립니다.\n" sendtext += "(현재 역삼동만 서비스하고 있습니다)\n" bot.send_message(chat_id=chat_id, text=sendtext, parse_mode='HTML') sendtext = message_create('help') bot.send_message(chat_id=chat_id, text=sendtext, parse_mode='HTML') #알림 사용자 정보 없는 경우만 저장 telegrams = Telegram.objects.filter(chat_id=chat_id) if telegrams.count() == 0: telegram = Telegram(chat_id=chat_id) telegram.save() elif '/help' in text: sendtext = message_create('help') bot.send_message(chat_id=chat_id, text=sendtext, parse_mode='HTML') elif '/맛집' in text: arr = text.split(' ') if len(arr) >= 1: r_type = arr[1] #restaurants = Restaurant.objects.filter(r_type=r_type) restaurants = Restaurant.objects.filter( Q(name__contains=r_type) | Q(r_type__contains=r_type) | Q(addr__contains=r_type)) sel_obj = random.choice(restaurants) sendtext = " [{0}] 음식점 추천해드립니다.♡ \n\n" sendtext += "메인메뉴: {1} \n" sendtext += "주소: {2} " sendtext += "(<a href='https://map.kakao.com/?q={3}'>길찾기 바로가기</a>)\n" sendtext += "그외 메뉴(가격):\n" sendtext += "<pre>{4}</pre>" sendtext = sendtext.format(sel_obj.name, sel_obj.main_menu, sel_obj.addr, sel_obj.addr, sel_obj.content) bot.send_message(chat_id=chat_id, text=sendtext, parse_mode='HTML') elif '/알림설정' in text: telegrams = Telegram.objects.filter(chat_id=chat_id) if telegrams.count() == 0: telegram = Telegram(chat_id=chat_id) telegram.save() elif '/알림해제' in text: telegrams = Telegram.objects.filter(chat_id=chat_id) if telegrams.count() > 0: telegram = Telegram.objects.get(chat_id=chat_id) telegram.delete() else: pass # bot.send_photo(chat_id=chat_id, photo='https://telegram.org/img/t_logo.png') #sendtext="test33" # bot.send_message(chat_id=chat_id, text=sendtext) except: pass return render(request, 'chatbot/index.html')
import telegram as tg, config as conf data = tg.getUpdates(conf.token) updatesNum = len(data['result']) # tg gives max 100 updates # get more updates till there are none while updatesNum > 0: for update in data['result']: try: if update['channel_post']['chat']['username'] == conf.channelID[ 1:]: if 'new_chat_title' in update['channel_post']: postID = update['channel_post']['message_id'] tg.delete(conf.token, conf.channelID, postID) except KeyError: pass try: # get content of the message message = update['message']['text'] except KeyError: # if key doesn't exist, discard update and go to the next update continue chatID = update['message']['chat']['id'] # try block added 2021-01 # after user without username caused endless spam on the server try: username = update['message']['from']['username']