Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23247

Python , Websockets , APIi , Unity , Game development [closed]

$
0
0

We are trying to develop a game. At this point, what we are trying to achieve is getting information of TikTok live broadcasts. Comment events, like events or gift events etc. This kind of information.

So far we got help from ChatGPT and wrote this Python code which basically gives us like, comment and gift events.

PYTHON CODE

import asyncioimport websocketsfrom TikTokLive import TikTokLiveClientfrom TikTokLive.events import CommentEvent, LikeEvent, GiftEventimport loggingimport json  # Setup basic logginglogging.basicConfig(level=logging.INFO)# Create the TikTokLiveClientclient = TikTokLiveClient(unique_id="@NAME OF TIKTOKER")# Dictionaries to store team assignments, likes count, and gifts countteam_likes = {}# Set to keep track of connected WebSocket clientsconnected = set()# WebSocket handler functionasync def ws_handler(websocket, path):    connected.add(websocket)    try:        await websocket.wait_closed()    finally:        connected.remove(websocket)# Function to broadcast messages to all connected clientsasync def broadcast(message):    message_json = json.dumps(message)      if connected:        await asyncio.gather(*(ws.send(message_json) for ws in connected))# Handlers for TikTok events that include broadcasting the informationasync def on_comment(event: CommentEvent):    nickname = event.user.nickname    unique_id = event.user.unique_id    comment = event.comment.strip().upper()    user_key = f"{nickname} ({unique_id})"    message = {"nickname": nickname,"unique_id": unique_id,"action": "comment","comment": comment        }    logging.info(f"{nickname} ({unique_id}) has joined team {comment}")    await broadcast(message)async def on_like(event: LikeEvent):    nickname = event.user.nickname    unique_id = event.user.unique_id    user_key = f"{nickname} ({unique_id})"    # Lets create a dictionary to count likes of user    if user_key not in team_likes:        team_likes[user_key] = 0     team_likes[user_key] += 1     message = {"nickname": nickname,"unique_id": unique_id,"action": "like","total_likes": team_likes[user_key]    }    # Update Log    logging.info(f"{nickname} ({unique_id}) has sent a total of {team_likes[user_key]} likes")    # Broadcast message via WebSocket    await broadcast(message)async def on_gift(event: GiftEvent):    nickname = event.user.nickname    unique_id = event.user.unique_id    gift_name = event.gift.name    message = {"nickname": nickname,"unique_id": unique_id,"action": "gift","gift_name": gift_name,    }    logging.info(f"{nickname} ({unique_id}) has sent '{gift_name}'")    await broadcast(message)# Add the comment, like, and gift event listeners to the TikTok clientclient.add_listener(CommentEvent, on_comment)client.add_listener(LikeEvent, on_like)client.add_listener(GiftEvent, on_gift)# Run the TikTok client and WebSocket server togetherasync def main():    async with websockets.serve(ws_handler, "localhost", 6789) as server:        tiktok_task = asyncio.create_task(client.start())        await asyncio.gather(tiktok_task)  # Await TikTok client task        await server.wait_closed()  # This line is no longer needed and should be removedif __name__ == '__main__':    asyncio.run(main())

HTML PART

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>WebSocket Test</title></head><body><h1>WebSocket Test</h1><p>Status: <span id="status">Not Connected</span></p><ul id="messages"></ul><input type="text" id="messageInput" placeholder="Your Message"/><button onclick="sendMessage()">SEND</button><script>        var ws;        function startWebSocket() {            ws = new WebSocket('ws://localhost:6789');            ws.onopen = function() {                document.getElementById('status').textContent = 'Connected';            };            ws.onmessage = function(event) {                var messages = document.getElementById('messages');                var message = document.createElement('li');                message.textContent = event.data;                messages.appendChild(message);            };            ws.onclose = function() {                document.getElementById('status').textContent = 'Connection Closed';                // Try to reconnect when server is closed \\                setTimeout(startWebSocket, 5000);            };            ws.onerror = function() {                document.getElementById('status').textContent = 'Something Went Wrong';            };        }        function sendMessage() {            var message = document.getElementById('messageInput').value;            if (message && ws.readyState === WebSocket.OPEN) {                ws.send(message);            }        }        window.onload = startWebSocket;</script></body></html>

At this point what we are trying to do is turning these informations into an API. Then we want to integrate these informations into UNITY.

How can we do this ? Or is it possible to achieve this goal ?

Any suggestion or help would be appreciated


Viewing all articles
Browse latest Browse all 23247

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>