예제 #1
0
def ask_lydia(user_id, lydia_query, coffeehouse_api_key):
    lydia = LydiaAI(coffeehouse_api_key)
    conn = sqlite3.connect('db.sqlite3')
    curr = conn.cursor()
    curr.execute(f'SELECT * FROM lydia WHERE user_id="{user_id}"')
    rows = curr.fetchall()

    if rows == []:
        session = lydia.create_session()
        curr.execute(
            f'INSERT INTO lydia VALUES ("{user_id}","{session.id}","{session.expires}")'
        )
        conn.commit()
        conn.close()
        return session.think_thought(lydia_query[1:])
    else:
        if int(time.time()) > int(rows[0][2]):
            curr.execute(f'DELETE FROM lydia WHERE (user_id = "{user_id}")')
            session = lydia.create_session()
            curr.execute(
                f'INSERT INTO lydia VALUES ("{user_id}","{session.id}","{session.expires}")'
            )
            conn.commit()
            conn.close()
            return session.think_thought(lydia_query[1:])
        else:
            conn.close()
            return lydia.think_thought(rows[0][1], lydia_query[1:])
예제 #2
0
파일: lydia.py 프로젝트: kmacprt/Nana-Remix
async def lydia_private(_client, message):
    global lydia_status, coffeehouse_api, lydia, session
    if lydia_api == "":
        await message.edit(
            "`lydia API key is not set!\nSet your lydia API key by adding Config Vars in heroku with "
            "name lydia_api with value your lydia key API`")
        return
    if lydia_status:
        await message.edit("Turning off lydia...")
        asyncio.sleep(0.5)
        lydia_status = False
        await message.edit("Lydia will not reply your message")
    else:
        await message.edit("Turning on lydia...")
        try:
            coffeehouse_api = API(lydia_api)
            # Create Lydia instance
            lydia = LydiaAI(coffeehouse_api)
            # Create a new chat session (Like a conversation)
            session = lydia.create_session()
        except:
            await message.edit("Wrong lydia API key!")
            return
        lydia_status = True
        await message.edit("now Lydia will reply your message!")
예제 #3
0
async def lydia_disable_enable(event):
    if event.fwd_from:
        return
    if Config.LYDIA_API is None:
        await event.edit(
            "please add required `LYDIA_API` env var,get it from coffeehouse.intellivoid.net"
        )
        return
    else:
        api_key = Config.LYDIA_API
        api_client = API(api_key)
        lydia = LydiaAI(api_client)

    input_str = event.pattern_match.group(1)

    if event.reply_to_msg_id is not None or input_str == "list" or event.is_private:
        reply_msg = None
        user_id = None
        chat_id = event.chat_id
        if event.is_private:
            user_id = event.chat_id
        if event.reply_to_msg_id is not None:
            reply_msg = await event.get_reply_message()
            user_id = reply_msg.from_id
        await event.edit("Processing...")
        if input_str == "enable":
            session = lydia.create_session()
            logger.info(session)
            logger.info(add_s(user_id, chat_id, session.id, session.expires))
            await event.edit(f"Hello there {user_id}!")
        elif input_str == "disable":
            logger.info(remove_s(user_id, chat_id))
            await event.edit(f"No, no, no, i am out.")
        elif input_str == "list":
            lsts = get_all_s()
            if len(lsts) > 0:
                output_str = "AI enabled users:\n\n"
                for lydia_ai in lsts:
                    output_str += f"[user](tg://user?id={lydia_ai.user_id}) in chat `{lydia_ai.chat_id}`\n"
            else:
                output_str = "no Lydia AI enabled users / chats. Start by replying `.enableai` to any user in any chat!"
            if len(output_str) > Config.MAX_MESSAGE_SIZE_LIMIT:
                with io.BytesIO(str.encode(output_str)) as out_file:
                    out_file.name = "lydia_ai.text"
                    await borg.send_file(event.chat_id,
                                         out_file,
                                         force_document=True,
                                         allow_cache=False,
                                         caption="Lydia AI enabled users",
                                         reply_to=event)
            else:
                await event.edit(output_str)
        else:
            await event.edit(
                "Reply To User Message to Add / Delete them from Lydia Auto-Chat."
            )
    else:
        await event.edit(
            "Reply To A User's Message to Add / Delete them from Lydia Auto-Chat."
        )
예제 #4
0
async def lydia_disable_enable(event):
    if event.fwd_from:
        return
    if ENV.LYDIA_API is None:
        await event.edit("Please add required `LYDIA_API` enviroment variable."
                         )
        return
    else:
        api_key = ENV.LYDIA_API
        api_client = API(api_key)
        lydia = LydiaAI(api_client)

    input_str = event.pattern_match.group(1)

    if event.reply_to_msg_id is not None or input_str == "list" or event.is_private:
        reply_msg = None
        user_id = None
        chat_id = event.chat_id
        if event.is_private:
            user_id = event.chat_id
        if event.reply_to_msg_id is not None:
            reply_msg = await event.get_reply_message()
            user_id = reply_msg.from_id
        # await event.edit("Processing...")
        if input_str == "enable":
            session = lydia.create_session()
            logger.info(session)
            logger.info(add_s(user_id, chat_id, session.id, session.expires))
            await event.edit(f"Lydia mode activated!")
        elif input_str == "disable":
            logger.info(remove_s(user_id, chat_id))
            await event.edit(f"Lydia was yeeted by CyberDoge.")
        elif input_str == "list":
            lsts = get_all_s()
            if len(lsts) > 0:
                output_str = "AI enabled users:\n\n"
                for lydia_ai in lsts:
                    output_str += f"[user](tg://user?id={lydia_ai.user_id}) in chat `{lydia_ai.chat_id}`\n"
            else:
                output_str = "No Lydia AI enabled users / chats. Start by replying `.enableai` to any user in any chat!"
            if len(output_str) > ENV.MAX_MESSAGE_SIZE_LIMIT:
                with io.BytesIO(str.encode(output_str)) as out_file:
                    out_file.name = "lydia_ai.text"
                    await borg.send_file(event.chat_id,
                                         out_file,
                                         force_document=True,
                                         allow_cache=False,
                                         caption="Lydia AI enabled users",
                                         reply_to=event)
            else:
                await event.edit(output_str)
        else:
            await event.edit(
                "Reply to a user's message to add / delete them from lydia ai-chat."
            )
    else:
        await event.edit(
            "Reply to a user's message to add / delete them from Lydia ai-chat."
        )
예제 #5
0
    CallbackContext,
    CommandHandler,
    Filters,
    MessageHandler,
    run_async,
)
from telegram.utils.helpers import mention_html

import ShasaBot.modules.sql.chatbot_sql as sql
from ShasaBot import AI_API_KEY, dispatcher
from ShasaBot.modules.helper_funcs.chat_status import user_admin
from ShasaBot.modules.helper_funcs.filters import CustomFilters
from ShasaBot.modules.log_channel import gloggable

CoffeeHouseAPI = API(AI_API_KEY)
api_client = LydiaAI(CoffeeHouseAPI)


@run_async
@user_admin
@gloggable
def add_chat(update: Update, context: CallbackContext):
    global api_client
    chat = update.effective_chat
    msg = update.effective_message
    user = update.effective_user
    is_chat = sql.is_chat(chat.id)
    if chat.type == "private":
        msg.reply_text("You can't enable AI in PM.")
        return
예제 #6
0
import coffeehouse as cf

import asyncio
import io
from sql_helpers.lydia_ai_sql import get_s, get_all_s, add_s, remove_s
from time import time
from uniborg.util import admin_cmd
from sample_config import Config
from coffeehouse.lydia import LydiaAI
from coffeehouse.api import API

if Config.LYDIA_API is not None:
    api_key = API(Config.LYDIA_API)
    # Initialise client
    api_client = LydiaAI(api_key)


@borg.on(admin_cmd(pattern="(ena|del|lst)cf", allow_sudo=True))
async def lydia_disable_enable(event):
    if event.fwd_from:
        return
    if Config.LYDIA_API is None:
        await event.edit("please add required `LYDIA_API` env var")
        return
    if event.reply_to_msg_id is not None:
        input_str = event.pattern_match.group(1)
        reply_msg = await event.get_reply_message()
        user_id = reply_msg.from_id
        chat_id = event.chat_id
        await event.edit("Processing...")
예제 #7
0
from xtraplugins.dB.lydia import (
    remove_chat,
    add_chat,
    get_all_chats,
    get_session,
    update_session
)

import asyncio, coffeehouse
import logging
from coffeehouse.lydia import LydiaAI

if Config.LYDIA_API_KEY:
    api_key = Config.LYDIA_API_KEY
    try:
        lydia = LydiaAI(api_key)
    except Exception as e:
        logging.error(f"Unable To Start Lydia Client \nTraceBack : {e}")
        lydia = None
else:
    lydia = None


def _check_lydia(func):
    @wraps(func)
    async def check_lydia(client, message):
        if not lydia:
            await edit_or_reply(message, "`Is Your Lydia Api Key Valid Or You Didn't Add It??`")
        elif lydia:
            await func(client, message)
    return check_lydia
예제 #8
0
from coffeehouse.lydia import LydiaAI
from coffeehouse.api import API
import asyncio
from telethon import events

# Non-SQL Mode
ACC_LYDIA = {}

if Var.LYDIA_API_KEY:
    api_key = Var.LYDIA_API_KEY
    api_client = API(api_key)
    lydia = LydiaAI(api_client)


@command(pattern="^.rep", outgoing=True)
async def repcf(event):
    if event.fwd_from:
        return
    await event.edit("Processing...")
    try:
        session = lydia.create_session()
        session_id = session.id
        reply = await event.get_reply_message()
        msg = reply.text
        text_rep = session.think_thought(msg)
        await event.edit("**sun bsdk**: {0}".format(text_rep))
    except Exception as e:
        await event.edit(str(e))


@command(pattern="^.autochat", outgoing=True)
예제 #9
0
import random
import asyncio
from time import time

from coffeehouse.api import API
from coffeehouse.lydia import LydiaAI, Session
from coffeehouse.exception import CoffeeHouseError
from pyrogram.errors.exceptions.bad_request_400 import PeerIdInvalid

from userge import userge, get_collection, Message, Filters, Config, pool

LYDIA_CHATS = get_collection("LYDIA_CHATS")
CH_LYDIA_API = os.environ.get("CH_LYDIA_API", None)
CUSTOM_REPLY_CHANNEL = int(os.environ.get("CUSTOM_REPLY_CHANNEL", 0))
if CH_LYDIA_API is not None:
    LYDIA = LydiaAI(API(CH_LYDIA_API))

ACTIVE_CHATS = {}
CUSTOM_REPLIES = []
QUEUE = asyncio.Queue()

LYDIA_API_INFO = """This module uses Lydia AI
Powered by CoffeeHouse API created by @Intellivoid.

Lydia is a Active Machine Learning Chat Bot.
Which can adapt to current user and chat with user
on any given topic."""


async def _init():
    async for chat in LYDIA_CHATS.find({'active': True}):
예제 #10
0
import io
from datetime import datetime
from time import time

from coffeehouse.api import API
from coffeehouse.lydia import LydiaAI

from . import BOTLOG, BOTLOG_CHATID
from .sql_helper.lydia_ai_sql import add_s, get_all_s, get_s, remove_s

if Config.LYDIA_API_KEY:
    api_key = Config.LYDIA_API_KEY
    # Create the coffeehouse API
    coffeehouse_api = API(api_key)
    # Create Lydia instance
    lydia = LydiaAI(coffeehouse_api)


@icssbot.on(admin_cmd(pattern="(en|re|li)ai$", outgoing=True))
@icssbot.on(sudo_cmd(pattern="(en|re|li)ai$", allow_sudo=True))
async def lydia_disable_enable(event):
    if event.fwd_from:
        return
    if Config.LYDIA_API_KEY is None:
        await edit_delete(event, "`Please add required LYDIA_API_KEY env var`",
                          10)
        return
    catevent = await edit_or_reply(event, "`.....`")
    input_str = event.pattern_match.group(1)
    if event.reply_to_msg_id is not None:
        reply_msg = await event.get_reply_message()
예제 #11
0
__MODULE__ = "Chatbot"
__HELP__ = """
An AI Powered Chat Bot Module

──「 **Chatbot** 」──
-> `addchat`
Enables AI on chat

-> `rmchat`
Removes AI on chat

Powered by CoffeeHouse API created by @Intellivoid.
"""

CoffeeHouseAPI = API(lydia_api)
api_ = LydiaAI(CoffeeHouseAPI)


@app.on_message(
    filters.user(AdminSettings) & filters.command("addchat", Command))
async def add_chat(_, message):
    global api_
    chat_id = message.chat.id
    is_chat = sql.is_chat(chat_id)
    if not is_chat:
        ses = api_.create_session()
        ses_id = str(ses.id)
        expires = str(ses.expires)
        sql.set_ses(chat_id, ses_id, expires)
        await edrep(message, text="`AI successfully enabled for this chat!`")
    else:
예제 #12
0
from coffeehouse.lydia import LydiaAI
from sample_config import Config
from telethon import events
from userbot import bot
from userbot.database.lydiadb import (get_ses, is_chat, list_chat, rem_chat,
                                      set_ses)
from userbot.util import admin_cmd

logging.basicConfig(level=logging.INFO)

if Config.LYDIA_API is not None:
    api_key = Config.LYDIA_API
    # Create the CoffeeHouse API instance
    coffeehouse_api = API(api_key)
    # Create Lydia instance
    lydia_session = LydiaAI(coffeehouse_api)


@bot.on(admin_cmd(pattern="cf"))
async def lydia_enable(event):
    if event.fwd_from:
        return
    if Config.MONGO_DB_URI and Config.LYDIA_API is None:
        await event.edit(
            "Make Sure You've added MONGO_URI and LYDIA_API env vars Correctly."
        )
        return
    await event.edit("Processing...")
    chat_id = event.chat_id
    is_chatt = await is_chat(chat_id)
    if not is_chatt:
예제 #13
0
파일: lydia.py 프로젝트: hanuraiga/gabot-3
Userbot module to use an AI To respond to people
"""
import asyncio

from coffeehouse.lydia import LydiaAI
from coffeehouse.api import API
from userbot import LYDIA_API_KEY
from userbot import CMD_HELP
from userbot.events import register

# Non-SQL Mode
ACC_LYDIA = {}
SESSION_ID = {}

if LYDIA_API_KEY:
    lydiaAI = LydiaAI(API(LYDIA_API_KEY))


@register(outgoing=True, pattern="^.repcf$")
async def repcf(event):
    if event.fwd_from:
        return
    await event.edit("Processing...")
    try:
        session = lydiaAI.create_session()
        reply = await event.get_reply_message()
        msg = reply.text
        text_rep = session.think_thought(msg)
        await event.edit("**Lydia says**: {0}".format(text_rep))
    except Exception as e:
        await event.edit(str(e))
예제 #14
0
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Uses Coffehouse API: https://coffeehouse.intellivoid.net/

from coffeehouse.lydia import LydiaAI
from telethon import events
from TamokutekiBot import COLLECTION, COFFEEHOUSE_ACCESS_KEY
from TamokutekiBot.helpers import command

import asyncio
import time

if COLLECTION:
    lydia = LydiaAI(COFFEEHOUSE_ACCESS_KEY)

    async def get_settings():
        data = await COLLECTION.find_one({'type': 'lydia-settings'})
        return data

    async def update_settings(new_settings):
        await COLLECTION.replace_one(await get_settings(), new_settings)

    async def get_data():
        data = await get_settings()
        if not data:
            data = {'type': 'lydia-settings', 'users': {}}
            await COLLECTION.insert_one(data)
        return data