Val Town Code SearchReturn to Val Town

API Access

You can access search results via JSON API by adding format=json to your query:

https://codesearch.val.run/image-url.jpg%20%22Optional%20title%22?q=api&page=67&format=json

For typeahead suggestions, use the /typeahead endpoint:

https://codesearch.val.run/typeahead?q=api

Returns an array of strings in format "username" or "username/projectName"

Found 12456 results for "api"(1892ms)

whatsapp-callbackindex.tsx26 matches

@yawnxyzUpdated 6 days ago
8// Environment variables should be set in your Val Town val's settings
9const WHATSAPP_WEBHOOK_VERIFY_TOKEN = Deno.env.get("WHATSAPP_WEBHOOK_VERIFY_TOKEN");
10const WHATSAPP_GRAPH_API_TOKEN = Deno.env.get("WHATSAPP_GRAPH_API_TOKEN");
11const WHATSAPP_BUSINESS_ID = Deno.env.get("WHATSAPP_BUSINESS_ID");
12const GROQ_API_KEY = Deno.env.get("GROQ_API_KEY"); // For the new quick ack
13
14// URL of YOUR Cloudflare Worker that orchestrates MCP calls & has /initiate-async-chat
46// --- Helper Functions ---
47async function sendWhatsAppMessage(phoneNumber, businessId, text, originalMessageId) {
48 if (!WHATSAPP_GRAPH_API_TOKEN || !businessId) {
49 console.error("WhatsApp API token or business ID is missing. Cannot send message.");
50 return;
51 }
58 method: "POST",
59 headers: {
60 "Authorization": `Bearer ${WHATSAPP_GRAPH_API_TOKEN}`,
61 "Content-Type": "application/json",
62 },
90 let messageToSend = "Hmm, let me look into that for you!"; // Default deferral message
91
92 if (!GROQ_API_KEY) {
93 console.warn("[SmartAck] GROQ_API_KEY missing. Sending static deferral ack.");
94 await sendWhatsAppMessage(phoneNumber, businessId, messageToSend, originalMessageId);
95 return { action: "defer_to_worker", messageSent: messageToSend };
177 try {
178 console.log(`[SmartAck] Attempting to generate smart ack for: "${userQuery.substring(0, 50)}..." with ${QUICK_ACK_MODEL}`);
179 const groqResponse = await fetch("https://api.groq.com/openai/v1/chat/completions", {
180 method: "POST",
181 headers: {
182 "Authorization": `Bearer ${GROQ_API_KEY}`,
183 "Content-Type": "application/json",
184 },
198 if (!groqResponse.ok) {
199 const errorText = await groqResponse.text().catch(() => "Could not retrieve error text");
200 console.error(`[SmartAck] Error from Groq API: ${groqResponse.status} ${groqResponse.statusText}`, errorText);
201 // Fallback to deferral message
202 } else {
308 console.log(`[initiateChat] Sending to CF Orchestrator (${CLOUDFLARE_WORKER_ORCHESTRATOR_URL}/initiate-async-chat) for ${userIdentifier}:`, JSON.stringify(mcpPayload, null, 2));
309
310 const mcpApiResponse = await fetch(`${CLOUDFLARE_WORKER_ORCHESTRATOR_URL}/initiate-async-chat`, {
311 method: "POST",
312 headers: { "Content-Type": "application/json" },
314 });
315
316 if (!mcpApiResponse.ok) {
317 const errorText = await mcpApiResponse.text();
318 console.error(`[initiateChat] Error from CF Orchestrator for ${clientRequestId}: ${mcpApiResponse.status} ${mcpApiResponse.statusText}`, errorText);
319 await sendWhatsAppMessage(userIdentifier, businessPhoneNumberId, "Sorry, I couldn't start a session with the assistant.", originalMessageId);
320 return { error: true, details: errorText };
321 } else {
322 const mcpResponseData = await mcpApiResponse.json();
323 console.log(`[initiateChat] Response from CF Orchestrator for ${clientRequestId} (Status ${mcpApiResponse.status}):`, mcpResponseData);
324 return { error: false, data: mcpResponseData };
325 }
458 console.log(`[PROCESS] Smartly Acknowledging for ${userPhoneNumber} (hash: ${queryHash || 'N/A'}). Effective Query for Ack: "${userQueryForSmartAck.substring(0,50)}..."`);
459
460 if (WHATSAPP_GRAPH_API_TOKEN && business_phone_number_id) {
461 // 1. Mark as read (sends blue check for the CURRENT incoming message)
462 try {
463 console.log(`Marking read for ${userPhoneNumber} (msg_id: ${currentMessageId})`);
464 const markReadResp = await fetch(`https://graph.facebook.com/v22.0/${business_phone_number_id}/messages`, {
465 method: "POST", headers: {"Authorization": `Bearer ${WHATSAPP_GRAPH_API_TOKEN}`, "Content-Type": "application/json"},
466 body: JSON.stringify({messaging_product: "whatsapp", status: "read", message_id: currentMessageId}),
467 });
494
495 } else {
496 console.error("WHATSAPP_GRAPH_API_TOKEN or business_phone_number_id missing.");
497 }
498 } else if (waMessage) {
534 // This means for direct GET, you'd need to monitor this Val's `/cf-worker-updates` or provide one.
535
536 const userIdentifier = "direct_api_user_" + crypto.randomUUID();
537 const clientRequestId = crypto.randomUUID(); // Not used by initiateChat directly, but good practice
538
653// Handle sending the welcome message
654app.post("/send-welcome", async (c) => {
655 if (!WHATSAPP_GRAPH_API_TOKEN || !WHATSAPP_BUSINESS_ID) {
656 console.error("WhatsApp API token or Business ID is not configured.");
657 return c.json({ error: "Server configuration error: WhatsApp API token or Business ID is missing." }, 500);
658 }
659
686 method: "POST",
687 headers: {
688 "Authorization": `Bearer ${WHATSAPP_GRAPH_API_TOKEN}`,
689 "Content-Type": "application/json",
690 },
697 );
698
699 const responseData = await response.json().catch(() => ({ error: { message: "Received non-JSON response from WhatsApp API" } }));
700
701 if (!response.ok) {
702 console.error(`Error sending custom message to ${phoneNumber}: ${response.status} ${response.statusText}`, responseData);
703 return c.json({ error: `WhatsApp API Error: ${responseData.error?.message || response.statusText}`, details: responseData }, response.status > 0 ? response.status : 500);
704 }
705

TownieLoginRoute.tsx8 matches

@pomdtrUpdated 6 days ago
8 const { isAuthenticated, authenticate, error } = useAuth();
9 const [tokenValue, setTokenValue] = useState("");
10 const [apiKey, setApiKey] = useState("");
11 // const [invalid, setInvalid] = useState(""); // TODO
12
13 const handleSubmit = (e) => {
14 e.preventDefault();
15 authenticate(tokenValue, apiKey);
16 };
17
36 >
37 <div>
38 <label htmlFor="valtown-token" className="label">Val Town API Token</label>
39 <div style={{ fontSize: "0.8em", color: "#666" }}>
40 <p>
41 <a href="https://www.val.town/settings/api/new" target="_blank" rel="noreferrer">
42 Create a Val Town token here
43 </a>
58 </div>
59 <div>
60 <label htmlFor="anthropic-api-key" className="label">Anthropic API Key (optional)</label>
61 <input
62 type="password"
63 id="anthropic-api-key"
64 name="anthropic-key"
65 value={apiKey}
66 onChange={e => {
67 setApiKey(e.target.value);
68 }}
69 />

Flarum-Discussion-To-PlainTextapp.tsx2 matches

@tyler71Updated 6 days ago
122async function getDiscussionPosts(discussionId: string): Promise<PostT[]> {
123 // Used to get the list of post id's for the discussion.
124 const discussionRes = await fetch(`${server}/api/discussions/${discussionId}`);
125 const discussionResJson = await discussionRes.json();
126
134
135 await Promise.all(chunks.map(async (c: string[]) => {
136 const postRes = await fetch(`${server}/api/posts?filter[id]=${c.join(",")}`);
137 const postJson = await postRes.json();
138
222
223 try {
224 const response = await fetch("/api/share", {
225 method: "POST",
226 headers: {
GitHub-Release-Notes

GitHub-Release-Notesgithub.ts20 matches

@charmaineUpdated 6 days ago
26 let hasMorePages = true;
27
28 // GitHub API headers
29 const headers = {
30 "Accept": "application/vnd.github.v3+json",
31 "Authorization": `Bearer ${token}`,
32 "User-Agent": "GitHub-Release-Notes-Generator",
33 "X-GitHub-Api-Version": "2022-11-28",
34 };
35
39 while (hasMorePages) {
40 const url =
41 `https://api.github.com/repos/${owner}/${repo}/commits?since=${sinceISO}&until=${untilISO}&per_page=100&page=${page}`;
42 console.log(`Fetching page ${page}...`);
43
46 if (!response.ok) {
47 const error = await response.text();
48 throw new Error(`GitHub API error: ${response.status} - ${error}`);
49 }
50
77 prNumber: number,
78): Promise<GitHubPR | null> {
79 const url = `https://api.github.com/repos/${owner}/${repo}/pulls/${prNumber}`;
80
81 const response = await fetch(url, {
84 "Authorization": `Bearer ${token}`,
85 "User-Agent": "GitHub-Release-Notes-Generator",
86 "X-GitHub-Api-Version": "2022-11-28",
87 },
88 });
94 if (!response.ok) {
95 const error = await response.text();
96 throw new Error(`GitHub API error: ${response.status} - ${error}`);
97 }
98
109 commitSha: string,
110): Promise<GitHubPR[]> {
111 const url = `https://api.github.com/repos/${owner}/${repo}/commits/${commitSha}/pulls`;
112
113 const response = await fetch(url, {
116 "Authorization": `Bearer ${token}`,
117 "User-Agent": "GitHub-Release-Notes-Generator",
118 "X-GitHub-Api-Version": "2022-11-28",
119 },
120 });
126 if (!response.ok) {
127 const error = await response.text();
128 throw new Error(`GitHub API error: ${response.status} - ${error}`);
129 }
130
133
134/**
135 * Fetches issues referenced by a commit or PR using GitHub API
136 */
137async function fetchIssueReferences(
147 // If we have a PR number, check for issues closed by the PR
148 if (prNumber) {
149 const prIssuesUrl = `https://api.github.com/repos/${owner}/${repo}/pulls/${prNumber}/commits`;
150
151 const prResponse = await fetch(prIssuesUrl, {
154 "Authorization": `Bearer ${token}`,
155 "User-Agent": "GitHub-Release-Notes-Generator",
156 "X-GitHub-Api-Version": "2022-11-28",
157 },
158 });
161 const prCommits = await prResponse.json();
162
163 // Extract issue numbers from commit messages using the GitHub API pattern
164 for (const commit of prCommits) {
165 // Look for "Fixes #X", "Closes #X", "Resolves #X" patterns that GitHub recognizes
180 // Also check the timeline of the PR to find linked issues
181 if (prNumber) {
182 const timelineUrl = `https://api.github.com/repos/${owner}/${repo}/issues/${prNumber}/timeline`;
183
184 const timelineResponse = await fetch(timelineUrl, {
187 "Authorization": `Bearer ${token}`,
188 "User-Agent": "GitHub-Release-Notes-Generator",
189 "X-GitHub-Api-Version": "2022-11-28",
190 },
191 });
213 * Fetches commits and their associated PRs
214 * Includes progress tracking for large repositories
215 * Uses GitHub API to find PR and issue references
216 */
217export async function fetchCommitsWithPRs(
231
232 // Process commits in batches to not get rate limited
233 const BATCH_SIZE = 5; // Reduced batch size since we're making more API calls per commit
234 for (let i = 0; i < commits.length; i += BATCH_SIZE) {
235 const batch = commits.slice(i, i + BATCH_SIZE);
236 const batchPromises = batch.map(async (commit) => {
237 // Use GitHub API to find associated PRs for this commit
238 const associatedPRs = await fetchPRsForCommit(token, owner, repo, commit.sha);
239
245 pr = associatedPRs[0]; // Use the first PR if multiple exist
246
247 // Get issue references using the GitHub API
248 const prIssueRefs = await fetchIssueReferences(token, owner, repo, commit.sha, pr.number);
249 issueRefs = [...prIssueRefs];
GitHub-Release-Notes

GitHub-Release-Notesllm.ts1 match

@charmaineUpdated 6 days ago
186`;
187
188 // Call the OpenAI API
189 const completion = await openai.chat.completions.create({
190 model: "gpt-4o",

Townieuser-summary.ts1 match

@jxnblkUpdated 6 days ago
20 SUM(num_images) as total_images
21 FROM ${USAGE_TABLE}
22 WHERE our_api_token = 1
23 GROUP BY user_id, username
24 ORDER BY total_price DESC

TownieuseProject.tsx2 matches

@jxnblkUpdated 6 days ago
2import { useAuth } from "./useAuth.tsx";
3
4const PROJECT_ENDPOINT = "/api/project";
5const FILES_ENDPOINT = "/api/project-files";
6
7export function useProject (projectId: string, branchId?: string) {

TownieuseProjects.tsx1 match

@jxnblkUpdated 6 days ago
2import { useAuth } from "./useAuth.tsx";
3
4const ENDPOINT = "/api/projects-loader";
5
6export function useProjects () {

TownieuseCreateProject.tsx1 match

@jxnblkUpdated 6 days ago
3import { useAuth } from "./useAuth.tsx";
4
5const ENDPOINT = "/api/create-project";
6
7export function useCreateProject () {

vapi-minutes-db2 file matches

@henrywilliamsUpdated 4 hours ago

social_data_api_project3 file matches

@tsuchi_yaUpdated 3 days ago
papimark21
socialdata
Affordable & reliable alternative to Twitter API: ➡️ Access user profiles, tweets, followers & timeline data in real-time ➡️ Monitor profiles with nearly instant alerts for new tweets, follows & profile updates ➡️ Simple integration