0% found this document useful (0 votes)
171 views

Final Code

This document contains the code for a Discord chatbot. The chatbot can respond to help commands, retrieve news based on user queries, and log user messages and metadata to a SQLite database. It uses several Python libraries like Discord.py, requests, and SQLite3. When a user sends a message, the bot logs the username, user ID, message content, and timestamp to the database. It can also return news search results from the News API or help information based on user commands.

Uploaded by

api-437658917
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
171 views

Final Code

This document contains the code for a Discord chatbot. The chatbot can respond to help commands, retrieve news based on user queries, and log user messages and metadata to a SQLite database. It uses several Python libraries like Discord.py, requests, and SQLite3. When a user sends a message, the bot logs the username, user ID, message content, and timestamp to the database. It can also return news search results from the News API or help information based on user commands.

Uploaded by

api-437658917
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

##

#import getpass
#getpass.getpass("pass")
##
import discord
import asyncio
import requests
import json
import urllib.parse
from discord.ext import commands
import time
from discord.ext.commands import Bot
import smtplib
import sqlite3
#from chatterbot import ChatBot
#from chatterbot.trainers import ListTrainer
#import os
##########################################
client = discord.Client()
client_command = commands

@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
##########################################
@client.event
async def on_message(message):
content = message.content
channel = message.channel
UserRequest = message.content.lower()
userId = message.author.id
userName = message.author.name
timestamp = message.timestamp
strtimestapm = str(message.timestamp)
#_Final_U_INFO = ("#User Name: "+userName+" #User ID: "+userId+" #User's
Message: "+content)
aa = str("#User Name: "+userName+" #User ID: "+userId+" #Content:
"+content+" #Timestamp:"+ strtimestapm)

##########################################
if UserRequest == "help" or UserRequest == "!help":
await client.send_message(channel,"For getting news ,please use '!news'
command.___________ ")
#For sending e-mail please use '!sendemail'command => command '!mymail'
=> command'!mypass' => command'!receiver' => command '!subject' => command
'!content'.MAKE SURE THAT YOU ARE SENDING FROM gmail.com ACCOUNT,OTHERWISE
YOU CANNOT SEND ANY EMAIL CURRENTLY.")#For chatting with just write
something I will respond.")
#await client.send_message(channel,userId)This and next lines of code
is for giving user ID and name on discord respectively,of course if user
want.However I have not added this option.
#await client.send_message(channel, "<@%s>" % (userId))
#print(userId)
#print("@"+userName)
##########################################
elif message.content.lower() == '!sendemail':
if message.content.lower().startswith('!mymail'):
mymail_ = message.content
if message.content.lower().startswith('!mypass'):
mymailpass_ = message.content
if message.content.lower().startswith('!receiver'):
receiver_ = message.content
if message.content.lower().startswith('!subject'):
subject_ = message.content
if message.content.lower().startswith('!content'):
Mcontent_ = message.content
def send_email(subject_, Mcontent_):
try:
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(mymail_,mymailpass_)
message = 'Subject: {}\n\n{}'.format(subject_, Mcontent_)
server.sendmail(receiver_,receiver_ , message)
server.quit()
print("Email sent!")
#await client.send_message(channel,"Email sent!")
except:
print("Email failed to send.")
#await client.send_message(channel,"Email failed to
send.")
#THIS COMMNAD DID NOT WORKED ,ALTHOUGH I REALLY TRIED TO INCLUD THIS
FUNCTION ON MY CHATBOT ASWELL.
##########################################
elif message.content.lower().startswith('!news'):
oldUserRequest1 = message.content.lower()
UserRequest1 = oldUserRequest1.replace('!news', '')#to remove '!news'
from the keyword
content1 = message.content

encoded = urllib.parse.quote(UserRequest1)

apiAdd2 = "https://newsapi.org/v2/everything?"
keywords2 = 'q='+ encoded
apikey = "&apikey=9430b58b162f4318bf862402d40a634d"
url2 = apiAdd2 + keywords2 + apikey
try:
jsonData2 = requests.get(url2).json()
except:
print("The link is not established!")
await client.send_message(channel,"The link is not established!")
print(url2)
subject__ = userName+"'s message"
def send_email(subject_, Mcontent_):
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login('[email protected]','kGP9Z5E1ZiEJsLA')
message = 'Subject: {}\n\n{}'.format(subject__, Mcontent_)
if userName == "ChatBot-D2":#I did not want to send bot messages to
the Email address.
pass
#if message.content.lower().startswith('!sendemail'):#line 113 and
118.AttributeError: 'str' object has no attribute 'content'
#pass
else:
server.sendmail('[email protected]','[email protected]' , message)
server.quit()
send_email(subject__,aa)

for i in range(3):#ACTUALLTY THERE ARE MORE THAN 3 NEWS MOSTLY ,BUT I


DID NOT WANT TO SEND ALL OF THE PROVIDED DATA.
_a_ = jsonData2['articles'][i]['author']
_b_ = jsonData2['articles'][i]['title']
_c_ = jsonData2['articles'][i]['description']
_d_ = jsonData2['articles'][i]['url']
#_e_ = jsonData2['articles'][i]['urlToImage']FOR SENDING POSSIBLE
PICTURES OF NEWS TO THE USER.
_g_ = jsonData2['articles'][i]['publishedAt']
#_h_ = jsonData2['articles'][i]['content'] CONTENT OF THE NEWS.
await client.send_message(channel,_a_)
await client.send_message(channel,_b_)
await client.send_message(channel,_c_)
await client.send_message(channel,_d_)
#await client.send_message(channel,_e_)
await client.send_message(channel,_g_)
#await client.send_message(channel,_h_)
await
client.send_message(channel,"______________________________________________
__________")
i +=1
##########################################
subject__ = userName+"'s message"
def send_email(subject_, Mcontent_):#I DID COPY THE CODE AGAIN BECAUSE
PERVIOUS ONE WAS FOR NEWS COMMAND ONLY.
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login('[email protected]','kGP9Z5E1ZiEJsLA')
message = 'Subject: {}\n\n{}'.format(subject__, Mcontent_)
if userName == "ChatBot-D2":
pass
#if
message.content.lower().startswith('!sendemail'):#.AttributeError: 'str'
object has no attribute 'content'
#pass
else:
server.sendmail('[email protected]','[email protected]' , message)
server.quit()
send_email(subject__,aa)

#FOR SHOWING ON TERMINAL


print("UserName: @"+userName)
print("UserID: "+userId)
print("Message time: "+strtimestapm)
print("User's message: "+content)
print("__________________")
conn = sqlite3.connect('UrINFO.db')
c = conn.cursor()
##########################################
def create_table():
c.execute("CREATE TABLE IF NOT EXISTS stuffToPlot(UserName TEXT ,
UserID Real, Message TEXT, Time REAL)")

def dynamic_data_entry():
UserName = userName
UserID = userId
Message = content
Time = strtimestapm
c.execute("INSERT INTO stuffToPlot (UserName, UserID, Message, Time)
VALUES (?, ?, ?, ? )",(UserName, UserID, Message, Time))
conn.commit()
create_table()

dynamic_data_entry()
##########################################
client.run('NTE1OTE0MTYzMDA0ODk5MzI4.Dtsb3g.Kyp-_mqX9W--kGP9Z5E1ZiEJsLA')
##########################################

You might also like