RuntimeWarning , RuntimeError (Python Al Chat Bot on Discord Server) - python-3.x

My Aim: Be able to integrate Al Chatbot and Discord
import nltk
nltk.download('punkt')
from nltk.stem.lancaster import LancasterStemmer
stemmer=LancasterStemmer()
import numpy
import tflearn
import tensorflow
import random
import json
import pickle
import nest_asyncio
import asyncio
#---------------------------------------------------------------------------
import discord
import os
with open("intents.json") as file:
data=json.load(file)
print(data['intents'])
try:
with open("data.pickle","rb") as f:
words,labels,training,output=pickle.load(f)
except:
words=[]
labels=[]
docs_x=[]
docs_y=[]
for intent in data['intents']:
for pattern in intent['patterns']:
wrds=nltk.word_tokenize(pattern)
words.extend(wrds)
docs_x.append(wrds)
docs_y.append(intent["tag"])
if intent["tag"] not in labels:
labels.append(intent["tag"])
#remove duplicate
words=[stemmer.stem(w.lower()) for w in words if w != "?"]
words=sorted(list(set(words)))
labels=sorted(labels)
training=[]
output=[]
out_empty=[0 for _ in range(len(labels))]
for x, doc in enumerate(docs_x):
bag=[]
wrds=[stemmer.stem(w) for w in doc]
for w in words:
if w in wrds:
bag.append(1)
else:
bag.append(0)
output_row=out_empty[:]
output_row[labels.index(docs_y[x])]=1
training.append(bag)
output.append(output_row)
training=numpy.array(training)
output=numpy.array(output)
with open("data.pickle","wb") as f:
pickle.dump((words,labels,training,output),f)
tensorflow.compat.v1.reset_default_graph()
net=tflearn.input_data(shape=[None,len(training[0])])
net=tflearn.fully_connected(net,16)
net=tflearn.fully_connected(net,16)
net=tflearn.fully_connected(net,len(output[0]),activation="softmax")
net=tflearn.regression(net)
model=tflearn.DNN(net)
model.fit(training, output,n_epoch=10000,batch_size=16,show_metric=True )
model.save('C:/Users/Desktop/chatbot/model/model.tflearn')
model.load('C:/Users/Desktop/chatbot/model/model.tflearn')
def bag_of_words(s,words):
bag=[0 for _ in range(len(words))]
s_words=nltk.word_tokenize(s)
s_words=[stemmer.stem(word.lower()) for word in s_words]
for se in s_words:
for i,w in enumerate(words):
if w==se:
bag[i]=1
return numpy.array(bag)
def chat():
print("start talking with the bot (type quit to stop!")
while True:
inp=input("You:")
if inp.lower()=="quit":
break
results= model.predict([bag_of_words(inp,words)])[0]
# print("results:",results)
results_index=numpy.argmax(results)
if results[results_index]>0.7:
tag=labels[results_index]
print("tag:", tag)
for tg in data["intents"]:
if tg["tag"]==tag:
responses=tg['responses']
client=discord.Client() #FOR DISCORD--------------------------------------
async def on_message(message):
if inp.author == client.user:
return
if inp.content.startswith("$M-bot"):
response=responses.request(inp.content[7:])
await asyncio.sleep(5)
await inp.channel.send(response)
on_message(inp)
client.run("API KEY TAKEN FROM DISCORD for BOT")
print("Bot:",random.choice(responses))
else:
print("I didn't get that. Please try again")
chat()
Warnings and Errors (Pyconsole):
start talking with the bot (type quit to stop!
You:hello
tag: greeting
C:/Users/Desktop/chatbot/chatbot.py:154: RuntimeWarning: coroutine 'chat.<locals>.on_message' was never awaited
on_message(inp)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
File "F:\Anaconda\lib\site-packages\discord\client.py", line 713, in run
loop.run_forever()
File "F:\Anaconda\lib\asyncio\base_events.py", line 560, in run_forever
self._check_running()
File "F:\Anaconda\lib\asyncio\base_events.py", line 552, in _check_running
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "F:\Anaconda\lib\site-packages\discord\client.py", line 90, in _cleanup_loop
_cancel_tasks(loop)
File "F:\Anaconda\lib\site-packages\discord\client.py", line 75, in _cancel_tasks
loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
File "F:\Anaconda\lib\asyncio\base_events.py", line 592, in run_until_complete
self._check_running()
File "F:\Anaconda\lib\asyncio\base_events.py", line 552, in _check_running
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/Desktop/chatbot/chatbot.py", line 162, in <module>
chat()
File "C:/Users/Desktop/chatbot/chatbot.py", line 155, in chat
client.run("API KEY TAKEN FROM DISCORD for BOT")
File "F:\Anaconda\lib\site-packages\discord\client.py", line 719, in run
_cleanup_loop(loop)
File "F:\Anaconda\lib\site-packages\discord\client.py", line 95, in _cleanup_loop
loop.close()
File "F:\Anaconda\lib\asyncio\selector_events.py", line 89, in close
raise RuntimeError("Cannot close a running event loop")
RuntimeError: Cannot close a running event loop
PROBLEM: Hello Friends, I'm trying to make a chatbot that works on discord and can give its answers through the artificial intelligence model I built, but I am getting a RuntimeWarning: Enable tracemalloc to get the object allocation traceback and RuntimeError: This event loop is already running How can I solve these?

Your error is because you keep reinitiating discord.Client. In every program, there should be only one instance of discord.Client. If you want to make it spit out the last response, you should move client out of the loop. Set the bot's response to a global variable and have the bot spit out the global variable when a command is sent

arrangements:
import nltk
nltk.download('punkt')
from nltk.stem.lancaster import LancasterStemmer
stemmer=LancasterStemmer()
import numpy
import tflearn
import tensorflow
import random
import json
import pickle
import nest_asyncio
import asyncio
#-------------------------------------------------------------------------------
import discord
import os
with open("intents.json") as file:
data=json.load(file)
print(data['intents'])
client=discord.Client() #OUT OF LOOP
#client.event #LISTEN EVENTS
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("$M-bot"):
response=responses.request(message.content[7:])
await message.channel.send(response)
try:
with open("data.pickle","rb") as f:
words,labels,training,output=pickle.load(f)
except:
words=[]
labels=[]
docs_x=[]
docs_y=[]
for intent in data['intents']:
for pattern in intent['patterns']:
wrds=nltk.word_tokenize(pattern)
words.extend(wrds)
docs_x.append(wrds)
docs_y.append(intent["tag"])
if intent["tag"] not in labels:
labels.append(intent["tag"])
#remove duplicate
words=[stemmer.stem(w.lower()) for w in words if w != "?"]
words=sorted(list(set(words)))
labels=sorted(labels)
training=[]
output=[]
out_empty=[0 for _ in range(len(labels))]
for x, doc in enumerate(docs_x):
bag=[]
wrds=[stemmer.stem(w) for w in doc]
for w in words:
if w in wrds:
bag.append(1)
else:
bag.append(0)
output_row=out_empty[:]
output_row[labels.index(docs_y[x])]=1
training.append(bag)
output.append(output_row)
training=numpy.array(training)
output=numpy.array(output)
with open("data.pickle","wb") as f:
pickle.dump((words,labels,training,output),f)
tensorflow.compat.v1.reset_default_graph()
net=tflearn.input_data(shape=[None,len(training[0])])
net=tflearn.fully_connected(net,16)
net=tflearn.fully_connected(net,16)
net=tflearn.fully_connected(net,len(output[0]),activation="softmax")
net=tflearn.regression(net)
model=tflearn.DNN(net)
model.fit(training, output,n_epoch=5000,batch_size=16,show_metric=True )
model.save('C:/Users/Desktop/chatbot/model/model.tflearn')
model.load('C:/Users/Desktop/chatbot/model/model.tflearn')
def bag_of_words(s,words):
bag=[0 for _ in range(len(words))]
s_words=nltk.word_tokenize(s)
s_words=[stemmer.stem(word.lower()) for word in s_words]
for se in s_words:
for i,w in enumerate(words):
if w==se:
bag[i]=1
return numpy.array(bag)
def chat():
global responses #GLOBAL VARIABLES
global inp #GLOBAL VARIABLES
print("start talking with the bot (type quit to stop!")
while True:
inp=input("You:")
if inp.lower()=="quit":
break
results= model.predict([bag_of_words(inp,words)])[0]
# print("results:",results)
results_index=numpy.argmax(results)
if results[results_index]>0.7:
tag=labels[results_index]
print("tag:", tag)
for tg in data["intents"]:
if tg["tag"]==tag:
responses=tg['responses']
print("Bot:",random.choice(responses))
else:
print("I didn't get that. Please try again")
chat()
client.run("API KEY")

Related

Trying to make a cogs loader discord.py

So basically I was trying to make a cogs loder from a youtube toutorial(https://youtu.be/vQw8cFfZPx0)but i am getting some error and i dont know how to fix it. I am using anaconda navigator virtual environment in vscode. My anaconda navigator virtual environment name is disc
This is my file
import discord
import os
from discord.ext import commands
client = commands.Bot(command_prefix= "#")
#client.command()
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
#client.command()
async def unload(ctx, extension):
client.unload_extension(f"cogs.{extension}")
#client.command
async def reload(ctx, extension):
client.reload_extension(f"cogs.{extension}")
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
client.run('token')
Here is my cogs file
import discord
from discord.ext import commands
class Example(commands.cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_ready(self):
print("bot is online")
#commands.command()
async def ping(self, ctx):
await ctx.send("pong")
def setup(client):
client.add_cog(Example(client))
This is my terminal
PS C:\Users\Oindrieel\Desktop\bot> conda activate disc
PS C:\Users\Oindrieel\Desktop\bot> & C:/Users/Oindrieel/anaconda3/envs/disc/python.exe c:/Users/Oindrieel/Desktop/bot/bot.py
Traceback (most recent call last):
File "C:\Users\Oindrieel\anaconda3\envs\disc\lib\site-packages\discord\ext\commands\bot.py", line 606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\Users\Oindrieel\Desktop\bot\bot.py", line 21, in <module>
client.load_extension(f'cogs.{filename[:-3]}')
File "C:\Users\Oindrieel\anaconda3\envs\disc\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\Oindrieel\anaconda3\envs\disc\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.example' raised an error: TypeError: module() takes at most 2 arguments (3 given)
PS C:\Users\Oindrieel\Desktop\bot>
Your code in cogs file is all correct just a simple error. Just change the class Example(commands.cog): to class Example(commands.Cog): where c in Cog is capital. Just change this your code starts to work

How to get rid of this problem in openCV tkinter code

I am working on a facial recognition based attendance system .This is my first project so i am not well acquainted with how to deal with errors. I am stuck in the middle and don't know how to solve the error. My terminal displays the following error:
PS E:\Project Work> & "C:/Users/Naik Faheem/AppData/Local/Programs/
Python/Python39/python.exe" "e:/Project Work/test.py"
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Naik Faheem\AppData\Local\Programs\Python\
Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "e:\Project Work\test.py", line 62, in face_recog
img=recognize(img,clf,facecascade)
File "e:\Project Work\test.py", line 52, in recognize
coord= draw_boundary(img,facecascade,1.1,10,255,"Face",clf)
File "e:\Project Work\test.py", line 39, in draw_boundary
n="+".join(n)
TypeError: can only join an iterable
[ WARN:1] global C:\Users\runneradmin\AppD
I HAVE PUT MY ACTUAL CODE BELOW.This code is intended to read classifier.xml file that stores the trained dataset.
from tkinter import *
from PIL import Image, ImageTk
from tkinter import ttk
from tkinter import messagebox
import mysql.connector
import cv2
class Face_recognition:
def __init__(self,root):
self.root=root
self.root.title('Face Detection')
self.root.geometry('1500x800+0+0')
self.root.config(bg='gray')
title_lbl=Label(self.root,text='FACE RECOGNITION',
font=('times new roman',35,'bold'),bg='gray',fg='darkblue')
title_lbl.place(x=0,y=0,width=1500,height=40)
btn=Button(self.root,command=self.face_recog,text='Detect Face',
font=('times new roman',12,'bold'),bg='red')
btn.place(x=650,y=60,width=200,height=40)
def face_recog(self):
def draw_boundary(img,classifier,scaleFactor,minNeighbors,color,text,clf):
gray_image=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
features = classifier.detectMultiScale(gray_image,scaleFactor,minNeighbors)
coord= []
for (x,y,w,h) in features:
cv2.rectangle(img,(x,y),(x+w,y+h),255,3)
id,predict= clf.predict(gray_image[y:y+h,x:x+w])
confidence= int(100*(1-predict/300))
con= mysql.connector.connect( user='root', host='localhost',
password='',database='stu_details')
cur=con.cursor()
cur.execute("select name from stu_info where name= "+str(id-1))
n=cur.fetchone()
n="+".join(n)
if confidence>70:
cv2.putText(img,f"Name: {n}",(x,y-60),cv2.FONT_HERSHEY_COMPLEX,1,255,2)
else:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,255),4)
cv2.putText(img,"Unknown face",(x,y10),
cv2.FONT_HERSHEY_COMPLEX_SMALL,0.8,(255,255,255),3)
coord=[x,y,w,h]
return coord
def recognize(img,clf,facecascade):
coord= draw_boundary(img,facecascade,1.1,10,255,"Face",clf)
return img
facecascade= cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
clf= cv2.face.LBPHFaceRecognizer_create()
clf.read("classifier.xml")
video_cap=cv2.VideoCapture(0)
while True:
ret,img=video_cap.read()
img=recognize(img,clf,facecascade)
cv2.imshow("Welcome to face recognition",img)
if cv2.waitKey(1)==13:
break
video_cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
root=Tk()
app=Face_recognition(root)
root.mainloop()
Error fixed:
Register the records in an ascending id (e.g 1,2,3....)and this problem gets solved
Change your data type from int to varchar in your data base
to get rid of this error.

while tokenization I'm encountering this error

I am a newbie to programming and I tried to do some interesting stuffs and ended up here, while string tokenizing I encountered this error while I can't solve this atmost
code:
import re
def cw(text):
counts=dict()
text=text.lower()
words=re.split(r'[^\w]',text)
for i in words:
print(words)
if i !="":
if i not in words:
counts[i]=1
else:
counts[i]+=1
return counts
def input():
with open("input.txt",'r') as f:
text=f.read()
counts=cw(text)
sort=sorted(counts.items(),key=lambda pair: pair[1],reverse=True)
print(sort)
if __name__ == "__main__":
input()
Error is:
Traceback (most recent call last):
File "C:/Users/surya/AppData/Local/Programs/Python/Python37-32/okay.py", line 35, in <module>
input()
File "C:/Users/surya/AppData/Local/Programs/Python/Python37-32/okay.py", line 27, in input
counts=cw(text)
File "C:/Users/surya/AppData/Local/Programs/Python/Python37-32/okay.py", line 17, in cw
counts[i]+=1
KeyError: 'as'

Can't pickle <class 'pywintypes.datetime'>: attribute lookup datetime on pywintypes failed

I am using python 3.5 (32bit), win10-64bit, OpenOPC, and I have downloaded pywin32 build 64bit. I have run the following python code:
import OpenOPC
import time
opc=OpenOPC.client()
opc.connect('Matrikon.OPC.Simulation.1')
tags =['Random.Int4','Random.Real4']
while True:
try:
value = opc.read(tags,group='Group0',update=1)
print (value)
except OpenOPC.TimeoutError:
print ("TimeoutError occured")
time.sleep(5)
but I always get this error message:
Traceback (most recent call last): File "C:\Program Files
(x86)\Python35-32\lib\multiprocessing\queues.py", line 241, in _feed
obj = ForkingPickler.dumps(obj) File "C:\Program Files (x86)\Python35-32\lib\multiprocessing\reduction.py", line 50, in dumps
cls(buf, protocol).dump(obj)
_pickle.PicklingError: Can't pickle : attribute lookup datetime on pywintypes failed.
I have found a solution:
import OpenOPC
import time
import pywintypes
pywintypes.datetime = pywintypes.TimeType
opc=OpenOPC.client()
opc.servers()
opc.connect('Matrikon.OPC.Simulation.1')
tags =['Random.Int1','Random.Real4','Random.Int2','Random.Real8']
while True:
try:
value = opc.read(tags,group='Group0',update=1)
print (value)
except OpenOPC.TimeoutError:
print ("TimeoutError occured")
time.sleep(1)

python hangs even with exception handling

I've got a raspberry PI attached to a MCP3008 ADC which is measuring an analog voltage across a thermistor. I'm using the gpiozero python library for communication between the PI and ADC. My code below runs for several minutes and then spits out an error, and then hangs on function get_temp_percent. That function returns the average of five measurements from the ADC. I'm using Signal to throw an exception after 1 second of waiting to try to get past the hang, but it just throws an error and hangs anyway. It looks like nothing in my except statement is being read. Why am I not escaping the code hang?
import time
from gpiozero import MCP3008
from math import log
import pymysql.cursors
from datetime import datetime as dt
import signal
import os
def handler(signum, frame):
print('Signal handler called with signal', signum, frame)
raise Exception("Something went wrong!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
def get_temp_percent(pos=0):
x=[]
for i in range(0,5):
while True:
try:
signal.signal(signal.SIGALRM, handler)
signal.alarm(1)
adc = MCP3008(pos)
x.append(adc.value)
#adc.close()
except Exception as inst:
print('get_temp_percent {}'.format(inst) )
signal.alarm(0)
continue
break
signal.alarm(0)
time.sleep(.1)
return round(sum(x)/len(x),5)
def write_date(temp0):
<writes temp0 to mysql db >
# Connect to the database
connection = pymysql.connect(host='', user='', password='', db='',cursorclass = pymysql.cursors.DictCursor)
while True:
temp_percent = get_temp_percent()
print('Temp Percent = {}'.format(temp_percent) )
<some function that do some arithmetic to go temp_percent to temp0>
write_date(temp0)
print('Data Written')
time.sleep(1)
print('Sleep time over')
print('')
Function get_temp_percent causes the problem below
Signal handler called with signal 14 <frame object at 0x76274800>
Exception ignored in: <bound method SharedMixin.__del__ of SPI(closed)>
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/gpiozero/mixins.py", line 137, in __del__
super(SharedMixin, self).__del__()
File "/usr/lib/python3/dist-packages/gpiozero/devices.py", line 122, in __del__
self.close()
File "/usr/lib/python3/dist-packages/gpiozero/devices.py", line 82, in close
old_close()
File "/usr/lib/python3/dist-packages/gpiozero/pins/local.py", line 102, in close
self.pin_factory.release_all(self)
File "/usr/lib/python3/dist-packages/gpiozero/pins/__init__.py", line 85, in release_all
with self._res_lock:
File "/home/pi/Desktop/testing exceptions.py", line 13, in handler
raise Exception("Something went wrong!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
Exception: Something went wrong!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
It looks like your call to gpiozero does a lot of work behind the scenes.
When your exception is processed, the library is trying to clean up and gets stuck.
I took a quick look at the docs for the library and it looks like you may be able to keep hold of the pins so you can re-use them.
e.g.
import ...
adcs = {}
def get_adc_value(pos):
if pos not in adcs:
adcs[pos] = MCP3008(pos)
return adcs[pos].value
def get_temp_percent(pos=0):
x = []
for i in range(0, 5):
x.append(get_adc_value(pos))
time.sleep(.1)
return round(sum(x)/len(x),5)
while True:
temp_percent = get_temp_percent()
...

Resources