yukyo 3 years ago
commit
605c5439de

+ 8 - 0
mcapi/YoConfig.py

@@ -0,0 +1,8 @@
+
+import json
+
+with open('config.json') as jsonFile:
+    YoConfig = json.load(jsonFile)
+    jsonFile.close()
+
+#print(YoConfig['db']['choozmo_new']['MYSQL_PASSWORD'])

BIN
mcapi/__pycache__/YoConfig.cpython-39.pyc


BIN
mcapi/__pycache__/fastapi_yo.cpython-39.pyc


+ 30 - 0
mcapi/config.json

@@ -0,0 +1,30 @@
+{
+    "db": {
+        "choozmo_old": {
+            "MYSQL_HOST": "139.162.121.30",
+            "MYSQL_DB": "yo_test",
+            "MYSQL_USER": "choozmo",
+            "MYSQL_PASSWORD": "pAssw0rd",
+            "MYSQL_PORT": 33306
+        },
+        "choozmo_new": {
+            "MYSQL_HOST": "db.ptt.cx",
+            "MYSQL_DB": "yodb",
+            "MYSQL_USER": "choozmo",
+            "MYSQL_PASSWORD": "pAssw0rd",
+            "MYSQL_PORT": 3306
+        },
+        "yolocal": {
+            "MYSQL_HOST": "yukyo-pc",
+            "MYSQL_DB": "yodb",
+            "MYSQL_USER": "root",
+            "MYSQL_PASSWORD": "play680821",
+            "MYSQL_PORT": 3306
+        },
+        "choozmo_redis": {
+            "REDIS_HOST": "db.ptt.cx",
+            "REDIS_PASSWORD": "",
+            "REDIS_PORT": 6379
+        }
+    }
+}

+ 188 - 0
mcapi/fastapi_yo.py

@@ -0,0 +1,188 @@
+
+from YoConfig import YoConfig
+from typing import Optional
+from fastapi import FastAPI
+from fastapi.middleware.cors import CORSMiddleware
+
+from pytrends.request import TrendReq
+from datetime import tzinfo
+import datetime
+import mysql.connector
+from mysql.connector import Error
+
+from opencc import OpenCC
+
+app = FastAPI()
+cc = OpenCC('s2t')
+
+origins = [
+    "http://localhost:8081",
+]
+app.add_middleware(
+    CORSMiddleware,
+    allow_origins=origins,
+    allow_credentials=True,
+    allow_methods=["*"],
+    allow_headers=["*"],
+)
+
+connection = mysql.connector.connect(
+    host=YoConfig['db']['choozmo_new']['MYSQL_HOST'],
+    database=YoConfig['db']['choozmo_new']['MYSQL_DB'],
+    user=YoConfig['db']['choozmo_new']['MYSQL_USER'],
+    password=YoConfig['db']['choozmo_new']['MYSQL_PASSWORD']
+)
+
+cursor = connection.cursor(buffered=True)
+
+@app.get("/")
+def read_root():
+    return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+def read_item(item_id: int, q: Optional[str] = None):
+    return {"item_id": item_id, "q": q}
+
+
+@app.get("/ts_top")
+def get_ts_tops(tc: Optional[int] = 3):
+    if not connection.is_connected():
+        connection.connect()
+    sql = '(SELECT * FROM trending_searches ORDER BY ts_date DESC LIMIT 20) ORDER BY ts_rank LIMIT ' + str(tc)
+    cursor.execute(sql)
+    records = cursor.fetchall()
+    return records
+
+
+@app.get("/related_queries/{Keyword}")
+def get_related_queries(Keyword: str, u: Optional[str] = '', fd: Optional[str] = '2020-01-01', td: Optional[str] = str(datetime.date.today())):
+    save_userKw(Keyword, u)
+    if not connection.is_connected():
+        connection.connect()
+    sql = 'select * from related_queries where rq_kword = \''+ Keyword +'\' '
+    cursor.execute(sql)
+    #print(str(cursor.rowcount))
+    if not cursor.rowcount > 0:
+        pytrends = TrendReq(hl='zh-TW', tz=1200, geo='TW')
+        kw_list = []
+        kw_list.append(Keyword)
+        pytrends.build_payload(kw_list, cat=0, timeframe=fd +
+                               ' '+td, geo='TW', gprop='')
+        KWORD = kw_list[0]
+        rqdata = pytrends.related_queries()
+
+        try:
+            if not rqdata[KWORD]['rising'] is None:
+                for item in rqdata[KWORD]['rising'].values.tolist():
+                    sql = 'insert into related_queries(rq_kword,rq_relatedword,rq_count,rq_type) select \'' + \
+                        KWORD+'\',\'' + item[0] + '\',\'' + \
+                        str(item[1]) + '\',\'rising\' '
+                    sql = cc.convert(sql)
+                    cursor.execute(sql)
+            if not rqdata[KWORD]['top'] is None:
+                for item in rqdata[KWORD]['top'].values.tolist():
+                    sql = 'insert into related_queries(rq_kword,rq_relatedword,rq_count,rq_type) select \'' + \
+                        KWORD+'\',\'' + item[0] + '\',\'' + \
+                        str(item[1]) + '\',\'top\' '
+                    sql = cc.convert(sql)
+                    cursor.execute(sql)
+        except:
+            print(sql)
+        connection.commit()
+    else:
+        records = cursor.fetchall()
+        return records
+    sql = 'select * from related_queries where rq_kword = \''+ Keyword +'\' '
+    cursor.execute(sql)
+    records = cursor.fetchall()
+    return records
+
+@app.get("/related_topics/{Keyword}")
+def get_related_topics(Keyword: str, u: Optional[str] = '', fd: Optional[str] = '2020-01-01', td: Optional[str] = str(datetime.date.today())):
+    save_userKw(Keyword, u)
+    if not connection.is_connected():
+        connection.connect()
+    sql = 'select * from related_topics where rt_kword = \''+ Keyword +'\' '
+    cursor.execute(sql)
+    #print(str(cursor.rowcount))
+    if not cursor.rowcount > 0:
+        pytrends = TrendReq(hl='zh-TW', tz=1200, geo='TW')
+        kw_list = []
+        kw_list.append(Keyword)
+        pytrends.build_payload(kw_list, cat=0, timeframe=fd +
+                               ' '+td, geo='TW', gprop='')
+        KWORD = kw_list[0]
+        rtdata = pytrends.related_topics()
+        try:
+            if not rtdata[KWORD]['rising'] is None:
+                for item in rtdata[KWORD]['rising'].values.tolist():
+                    sql = 'insert into related_topics(rt_kword,rt_type,rt_value,rt_formattedValue,rt_link,rt_topic_mid,rt_topic_title,rt_topic_type) select \'' + KWORD+'\',\'rising\',\'' + str(
+                        item[0]) + '\',\'' + item[1] + '\',\'' + item[2] + '\',\'' + item[3] + '\',\'' + item[4] + '\',\'' + item[5] + '\' '
+                    sql = cc.convert(sql)
+                    cursor.execute(sql)
+            if not rtdata[KWORD]['top'] is None:
+                for item in rtdata[KWORD]['top'].values.tolist():
+                    sql = 'insert into related_topics(rt_kword,rt_type,rt_value,rt_hasData,rt_link,rt_topic_mid,rt_topic_title,rt_topic_type) select \'' + KWORD + \
+                        '\',\'top\',\'' + item[1] + '\',\'' + str(item[2]) + '\',\'' + item[3] + '\',\'' + \
+                        item[4] + '\',\'' + item[5] + '\',\'' + \
+                        item[6] + '\' '
+                    sql = cc.convert(sql)
+                    cursor.execute(sql)
+        except:
+            print(sql)
+        connection.commit()
+    else:
+        records = cursor.fetchall()
+        return records
+    sql = 'select * from related_topics where rt_kword = \''+ Keyword +'\' '
+    cursor.execute(sql)
+    records = cursor.fetchall()
+    return records
+
+def save_userKw(Keyword: str, Username: str = ''):
+    if not connection.is_connected():
+        connection.connect()
+    sql = 'insert into user_searches(us_username,us_search_word) select \''+ Keyword +'\',\''+ Username +'\' '
+    cursor.execute(sql)
+    return
+
+
+@app.get("/related_queries1/{Keyword}")
+def get_related_queries(Keyword: str, u: Optional[str] = '', fd: Optional[str] = '2020-01-01', td: Optional[str] = str(datetime.date.today())):
+    save_userKw(Keyword, u)
+    if not connection.is_connected():
+        connection.connect()
+    pytrends = TrendReq(hl='zh-TW', tz=1200, geo='TW')
+    kw_list = []
+    kw_list.append(Keyword)
+    pytrends.build_payload(kw_list, cat=0, timeframe=fd +
+                            ' '+td, geo='TW', gprop='')
+    KWORD = kw_list[0]
+    rqdata = pytrends.related_queries()
+
+    if not rqdata[KWORD]['rising'] is None:
+        return rqdata[KWORD]['rising'].values.tolist()
+    if not rqdata[KWORD]['top'] is None:
+        return rqdata[KWORD]['top'].values.tolist()
+    return
+
+
+@app.get("/related_topics1/{Keyword}")
+def get_related_topics(Keyword: str, u: Optional[str] = '', fd: Optional[str] = '2020-01-01', td: Optional[str] = str(datetime.date.today())):
+    save_userKw(Keyword, u)
+    if not connection.is_connected():
+        connection.connect()
+    pytrends = TrendReq(hl='zh-TW', tz=1200, geo='TW')
+    kw_list = []
+    kw_list.append(Keyword)
+    pytrends.build_payload(kw_list, cat=0, timeframe=fd +
+                            ' '+td, geo='TW', gprop='')
+    KWORD = kw_list[0]
+    rtdata = pytrends.related_topics()
+
+    if not rtdata[KWORD]['rising'] is None:
+        return rtdata[KWORD]['rising'].values.tolist()
+    if not rtdata[KWORD]['top'] is None:
+        return rtdata[KWORD]['top'].values.tolist()
+    return

+ 82 - 0
tgBot/MyTelegramBot.py

@@ -0,0 +1,82 @@
+
+from YoConfig import YoConfig
+import redis
+
+from random import randint
+from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, MessageHandler, Filters
+from telegram import InlineKeyboardMarkup, InlineKeyboardButton
+import telegram
+import datetime
+
+""" import logging
+logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
+                     level=logging.INFO) """
+
+""" def start(update, context):
+    context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!") """
+
+r = redis.Redis(host=YoConfig['db']['choozmo_redis']['REDIS_HOST'], port=YoConfig['db']['choozmo_redis']['REDIS_PORT'], db=0)
+
+def start(update, bot):
+    a, b = randint(1, 100), randint(1, 100)
+    update.message.reply_text('{} + {} = ?'.format(a, b),
+        reply_markup = InlineKeyboardMarkup([[
+                InlineKeyboardButton(str(s), callback_data = '{} {} {}'.format(a, b, s)) for s in range(a + b - randint(1, 3), a + b + randint(1, 3))
+            ]]))
+
+
+def answer(update, bot):
+    a, b, s = [int(x) for x in update.callback_query.data.split()]
+    if a + b == s:
+        update.callback_query.edit_message_text('你答對了!')
+    else:
+        update.callback_query.edit_message_text('你答錯囉!')
+
+updater = Updater('1773608337:AAF0TVRKXQu4vB3ii7JkM5kuV2vsXkvX7ss', use_context=True)
+j = updater.job_queue
+dispatcher = updater.dispatcher
+
+dispatcher.add_handler(CommandHandler('start', start))
+dispatcher.add_handler(CallbackQueryHandler(answer))
+
+def echo(update, context):
+    context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.text)
+
+echo_handler = MessageHandler(Filters.text & (~Filters.command), echo)
+dispatcher.add_handler(echo_handler)
+
+def caps(update, context):
+    text_caps = ' '.join(context.args).upper()
+    context.bot.send_message(chat_id=update.effective_chat.id, text=text_caps)
+
+caps_handler = CommandHandler('caps', caps)
+dispatcher.add_handler(caps_handler)
+
+
+def callback_alarm(context):
+    context.bot.send_message(chat_id=context.job.context, text='BEEP')
+
+def callback_timer(update, context):
+    context.bot.send_message(chat_id=update.message.chat_id,
+                             text='Setting a timer for 1 minute!')
+
+    context.job_queue.run_repeating(callback_alarm, 60, context=update.message.chat_id)
+
+timer_handler = CommandHandler('timer', callback_timer)
+dispatcher.add_handler(timer_handler)
+
+def callback_minute(context: telegram.ext.CallbackContext):
+    context.bot.send_message(chat_id='1053416326', 
+                             text='Im online.')
+    context.bot.send_message(chat_id='-1001177266889', 
+                             text='Im online.')    
+updater.job_queue.run_once(callback_minute, 3)
+
+def hhh_space_monitor(context: telegram.ext.CallbackContext):
+    context.bot.send_message(chat_id='-1001177266889', 
+                             text='this is space monitor. space_hhhapi: \n' + str(r.get('space_hhhapi')))    
+updater.job_queue.run_daily(hhh_space_monitor, datetime.time(00, 00, 00))
+updater.job_queue.run_once(hhh_space_monitor, 3)
+
+updater.start_polling()
+updater.idle()

+ 8 - 0
tgBot/YoConfig.py

@@ -0,0 +1,8 @@
+
+import json
+
+with open('config.json') as jsonFile:
+    YoConfig = json.load(jsonFile)
+    jsonFile.close()
+
+#print(YoConfig['db']['choozmo_new']['MYSQL_PASSWORD'])

+ 30 - 0
tgBot/config.json

@@ -0,0 +1,30 @@
+{
+    "db": {
+        "choozmo_old": {
+            "MYSQL_HOST": "139.162.121.30",
+            "MYSQL_DB": "yo_test",
+            "MYSQL_USER": "choozmo",
+            "MYSQL_PASSWORD": "pAssw0rd",
+            "MYSQL_PORT": 33306
+        },
+        "choozmo_new": {
+            "MYSQL_HOST": "db.ptt.cx",
+            "MYSQL_DB": "yodb",
+            "MYSQL_USER": "choozmo",
+            "MYSQL_PASSWORD": "pAssw0rd",
+            "MYSQL_PORT": 3306
+        },
+        "yolocal": {
+            "MYSQL_HOST": "yukyo-pc",
+            "MYSQL_DB": "yodb",
+            "MYSQL_USER": "root",
+            "MYSQL_PASSWORD": "play680821",
+            "MYSQL_PORT": 3306
+        },
+        "choozmo_redis": {
+            "REDIS_HOST": "db.ptt.cx",
+            "REDIS_PASSWORD": "",
+            "REDIS_PORT": 6379
+        }
+    }
+}