Skip to content

Feedback #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: feedback
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 132 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

#api keys
api_keys.json
Binary file added Literature review .docx
Binary file not shown.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
[![Review Assignment Due Date](https://classroom.github.com/assets/deadline-readme-button-24ddc0f5d75046c5622901739e7c5dd533143b0c8e959d652212380cedb1ea36.svg)](https://classroom.github.com/a/fSA_TVih)
[![Review Assignment Due Date](https://classroom.github.com/assets/deadline-readme-button-8d59dc4de5201274e310e4c54b9627a8934c3b88527886e3b421487c677d23eb.svg)](https://classroom.github.com/a/fSA_TVih)
[![Open in Visual Studio Code](https://classroom.github.com/assets/open-in-vscode-c66648af7eb3fe8bc4f294546bfd86ef473780cde1dea487d3c4ff354943c9ae.svg)](https://classroom.github.com/online_ide?assignment_repo_id=10680461&assignment_repo_type=AssignmentRepo)
## Final Project Repo

Expand Down
130 changes: 130 additions & 0 deletions api_filter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
from telethon.sync import TelegramClient
from datetime import datetime, timedelta
from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.types import ChannelParticipantsSearch
import json
import pytz
import statistics
from urllib.request import urlopen

class TelegramAPI:
def __init__(self):
with open('api_keys.json') as f:
keys = json.load(f)

self.api_id = keys['api_id']
self.api_hash = keys['api_hash']
self.bot_token = keys['bot_token']

def get_all_messages(self,username):
einelist = []
with TelegramClient('test', self.api_id, self.api_hash) as client:

#offset_date=lastweekcutoff
for message in client.iter_messages(username,reverse=False):
#finds all reaction types and converts it to likes
einelist.append(message)
#print(type(message.date))
#print(len(einelist))
return einelist

def filter_timeframe(self,einelist, timeframe):
now = datetime.now(pytz.timezone('US/Eastern'))

timeframes = {
'hour': timedelta(hours=1),
'day': timedelta(days=1),
'week': timedelta(weeks=1),
'month': timedelta(days=30), # Approximate one month
'year': timedelta(days=365),
'recent': timedelta.max
}

if timeframe not in timeframes:
raise ValueError(f"Invalid timeframe '{timeframe}', should be one of {list(timeframes.keys())}")

if timeframe == 'recent':
most_recent_item = max(einelist, key=lambda item: getattr(item, "date"))
return [most_recent_item]

start_time = now - timeframes[timeframe]

return [item for item in einelist if getattr(item, "date") >= start_time]

def filter_metric(self,einelist,metric,username=""):
timeframes = {
'reactions': [],
'comments': [],
'forwards': [],
'views': [],
}
for message in einelist:
reactions,comments,forwards,views = 0,0,0,0
if message.reactions != None:
messagereactions = message.reactions.results
for reacttype in messagereactions:
# print(reacttype.reaction)
# print(reacttype.count)
reactions += int(reacttype.count)

try:
if message.views != None:
views += int(message.views)
except:print("L")
try:
if message.forwards != None:
forwards += int(message.forwards)
except:print("L")

if message.replies != None:
comments += int(message.replies.replies)

timeframes['reactions'].append(reactions)
timeframes['comments'].append(comments)
timeframes['forwards'].append(forwards)
timeframes['views'].append(views)

return timeframes[metric]

def filter_stat(self,metriclist,stat):
if stat=="top":
return max(metriclist)
elif stat=="bottom":
return min(metriclist)
elif stat=="average":
return statistics.mean(metriclist)
elif stat=="median":
statistics.median(metriclist)
else:
return -1

def response_from_labels(self,timeframe,stat,metric,user):
fullacountlist = self.get_all_messages(user)
timefilteredlist = self.filter_timeframe(fullacountlist,timeframe)
metricfilteredlist = self.filter_metric(timefilteredlist,metric)
wantedstat = self.filter_stat(metricfilteredlist,stat)
return wantedstat

def get_follower_count(self,username):
url =f"https://api.telegram.org/bot{self.bot_token}/getChatMembersCount?chat_id=@{username}"
with urlopen(url) as f:
resp = json.load(f)

return int(resp['result'])






if __name__ == "__main__":
pass
# t = TelegramAPI()
# einelist = t.get_all_messages("")
# filteredlist = filter_timeframe(einelist,"day")
# print(filteredlist)
# print(len(filteredlist))


# print(filter_metric(filteredlist,"comments"))
# print(response_from_labels("recent","top","comments","disclosetv"))
30 changes: 30 additions & 0 deletions chatgptprompts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import requests
import json
import openai
import os


class ChatBot:
def __init__(self) -> None:
openai.api_key = os.environ.get("OPENAI_API_KEY")

self.messages = [
{"role": "system", "content": "You are a kind helpful social media assistant."},
]


def querychatgpt(self, initmessage,stat):
message = f"You are a helpful social media assistant for an account using Telegram. A user asks '{initmessage}'. The answer to this question is '{str(stat)}'. Please write a response to that and don't worry about missing context, and do not mention that you lack any context. Also try to keep the response in two sentences or under."
# print(message)

self.messages.append( {"role": "user", "content": message},)

chat = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=self.messages)

reply = chat.choices[0].message.content
self.messages.append({"role": "assistant", "content": reply})
return reply

# c = ChatBot()

# print(c.querychatgpt( "what was the average amount of likes i got in the last month?",12))
Loading